Extarcting string stored in coulmn as series values in mysql - mysql

I have a table which has column storing values as comma separated values.
I need to extarct specific value like '2' and 10 in ever row of the column.I tried substr but cannot arrive into result.How can we achieve this in msql
My table looks like as attached as screenshot

You could just use find_in_set():
select
channel,
find_in_set('2', channel) > 0 has_2,
find_in_set('10', channel) > 0 has_10
from mytable
This adds two columns to the table with a boolean value that indicates whether values 2 and 10 are available in channel.

Related

MySQL select value range within a value range, from a dash-separated column value?

How do I select a value range from a column where two values in it are separated by a dash, using MySQL?
Here's my example table named "example":
The user enters a low value (X) and a high value (Y).
For example X=2.5 and Y=7.2
I want to select all items where the left value is higher than X (in this case 2.5) and the right value is lower than Y (in this case 7.2). Using these X and Y values I should end up with the rows 2 and 5 as a result.
Sort of like this:
SELECT * FROM example WHERE MIN(value) > X AND MAX(value) < Y
How do I do this?
You can use LEFT and RIGHT functions to get X and Y out of your value field.
So I think you are looking for something like this:
SELECT * FROM example WHERE CAST(LEFT(value,3)AS DECIMAL(2,1)) > 2.5 and CAST(RIGHT(value,3)AS DECIMAL(2,1)) < 7.2
First you need to access your table in a fashion that only has one value per column. (Multiple values per column, like 3.5-7.5 happen to be a very common relational database design antipattern. They cripple both performance and clarity.)
This SQL subquery does the trick for pairs of values.
SELECT item_id, name,
0.0+SUBSTRING_INDEX(value, '-',1) first,
0.0+SUBSTRING_INDEX(value, '-', -1) last
FROM example;
The expression 0.0+something is a MySQL trick to coerce a value to be numeric.
Then use the subquery to apply your search criteria.
SELECT item_id, name, first, last
FROM ( SELECT item_id, name,
0.0+SUBSTRING_INDEX(value, '-',1) first,
0.0+SUBSTRING_INDEX(value, '-', -1) last
FROM example
) s
WHERE first > 2.5
AND last < 7.2;
Fiddle here.
In a comment you asked about the situation where you have more than two values in a single column separated by delimiters. See this. Split comma separated values in MySQL
Pro tip Don't put more than one number in a column in an RDBMS table. The next person to use the table will be muttering curses all day while trying to use that data.
Pro tip Use numeric data types, not VARCHAR(), for numbers.

SQL SELECT everthing with value 5 but not specify from which column

I have tried to select something with SQL, and I've a problem with it.
What I want:
SQL SELECT * FROM table WHERE ? = '5';
Select everything which = 5, BUT not specify from which column.
Example:
From this ""database"", you should receive the 1st and the last row.
Is that possible?
You have to list the columns but you can use in. The where clause looks like:
where 5 in (price, height)
Note: This assumes that the columns have the same type. You could get type conversion errors if they are not.
Also, given the names of the column and the data, I assume that the columns are stored as numbers. Hence, I dropped the single quotes around 5. If they are really strings, then use the single quotes.
you need to add a condition to your query with or keyword so if any of them match the row will be shown as a result
SELECT * FROM tablename WHERE price =5 or height= 5
better you list your columns by name instead of using * after SELECT

MYSQL - Replace 0 with a string and non 0 with another string in SQL query output, without Conditionals

I have a complex string that starts like this: SELECT COUNT(*) AS 'columnName' .... The result will display a positive or 0 number. What i want is in case it's 0 i want it to print string1 (instead of 0) and if it's higher than 0, i want it to print string2 (instead of that number). The caveat is that i don't want to use conditional statements, no ifs or cases. I've been thinking about a replace function, but i don't think it works. After that then maybe a VIEW (virtual table to store the results?) would work? I don't want to alter any original table data in any way, i just want to manipulate the output. I can't figure it out, I'm an SQL beginner. Help?
select COALESCE((select 'string1' as s
from table1
having count(*) < 0 )
,'string2')
Above query returns string 1 if there are no records in the table else it returns string 2
The correct approach is to use CASE, but there are other ways:
select elt(1 + least(count(*), 1), 'string1', 'string2')
count(*) almost never returns 0. It only returns 0 when there is no group by and the table has no rows (or all rows have been filtered out by the where.

MySQL In clause not giving the right result

In a MySQL table i have a field, containing this value for a given record : "1908,2315,2316"
Here is my sql Query :
SELECT * FROM mytable WHERE 2316 IN (myfield)
I got 0 results!
I tried this :
SELECT * FROM mytable WHERE 2315 IN (myfield)
Still 0 results
And then i tried this :
SELECT * FROM mytable WHERE 1908 IN (myfield)
Surprisingly i obtained the record when searching with 1908! What should i do to also obtain the record when searching with 2315 and 2316 ? What am i missing ?
Thanks
You appear to be storing comma delimited values in a field. This is bad, bad, bad. You should be using a junction table, with one row per value.
But, sometimes you are stuck with data in a particular structure. If so, MySQL provides the find_in_set() functions.
SELECT *
FROM mytable
WHERE find_in_set(2316, myfield) > 0;
You can't use IN() over comma separated list of no.s its better to normalize your structure first for now you can use find_in_set to find results matching with comma separated string
SELECT * FROM mytable WHERE find_in_set('1908',myfield) > 0
This question has been asked and answered before, but I don't want to hunt for it; this question should be closed as a duplicate. But, to answer your question:
The commas in the string, the column value, are just characters. Those are part of the string. They aren't seen as "separators" between values in the SQL text. The way SQL sees it, the column contains a single value, not a "list" of values.
So, in your query, the IN (field) is equivalent to an equals comparison. It's equivalent to comparing to a string. For example:
... WHERE 2316 = '1908,2315,2316'
And those aren't equal, so the row isn't returned. The "surprisingly" finding of a match, in the case of:
... WHERE 1908 IN ('1908,2315,2316')
that's explained because that string is being evaluated in a numeric context. That is, the comparison returns true, because all of these also true:
... WHERE 1908 = '1908,2315,2316' + 0
... WHERE 1908 = '1908xyz' + 0
... WHERE 1908 = '1907qrs' + 1
(When evaluated in a numeric context, a string gets converted to numeric. It just happens that the string evaluates to a numeric value that equals the integer value it's being comparing to.)
You may be able to make use of the MySQL FIND_IN_SET function. For example:
... WHERE FIND_IN_SET(2316,'1908,2315,2316')
But, please seriously reconsider the design of storing comma separated list. I recommend Bill Karwin's "SQL Antipatterns" book...
http://www.amazon.com/SQL-Antipatterns-Programming-Pragmatic-Programmers/dp/1934356557
In mysql IN clause is utilized as
SELECT * FROM mytable WHERE column_name IN (set_of_values) ;
Mention column name instead of values
Please try
SELECT * FROM mytable WHERE LOCATE(CONCAT (',', 2316 ','), CONCAT (',',myfield,',' ) ) <>0

Use comma separated list from one table as clause in query for another table

I have an events table with a field called breaks. This is populated with data in a comma separated format, i.e. 1,2,3 or 1 or 1,4,5 - the same format that MySQL's IN command uses.
I'd then like to run a query - on the slots table - to return all rows apart from those specified in events.breaks.
The query, theoretically, should be something like this:
SELECT
`slots`.`id` AS id,
RIGHT(`slots`.`time`, 8) AS `time`
FROM
`slots`, `event`
WHERE
`slots`.`id` NOT IN (`event`.`breaks`)
But that doesn't appear to work - if event.breaks is 4,5,7, the only row from the slots table that doesn't return is 4!
SQLFiddle here: http://sqlfiddle.com/#!2/913fe/1/0
You're passing a single field to the NOT IN () clause, not a subexpression. Think of it like this
(1, 2, 3)
is roughly the same as
SELECT 1
UNION
SELECT 2
UNION
SELECT 3;
as a subexpression. What you're doing instead is
('4,5,7')
which is roughly equivalent to
SELECT '4,5,7';
which in turn MySQL probably converted to a number for the comparison and the result is
NOT IN (4)
What you're actually trying to do isn't really supposed to be done like that. It'd be better if you added an AxB relation table so you can select several rows with the IDs you don't want.
Give this a try:
SELECT slots.id AS id, RIGHT(slots.time, 8) time
FROM slots, event
WHERE FIND_IN_SET(slots.id, event.breaks) = 0
This is how the FIND_IN_SET(str,strlist) function works:
Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. [...] Returns 0 if str is not in strlist or if strlist is the empty string.
Also note that IN (val1, val2, val3) is NOT the same as IN (val4) where val4 is a commma-separated string. The IN clause will compare by equality.
you may need a subselect to return the split string
... NOT IN (SELECT your_split_fnc(`event`.`breaks`) FROM `events`)
See answers here for a way to split strings in MySQL Can Mysql Split a column?
instr() MySQL function could be of help also
... INSTR(event.breaks,id) = 0
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_instr