MySQL - WHERE IN with a list into a field - mysql

I have a field ('roles') with this values
roles
row_1: 1,2,3,5
row_2: 2,13
I do this:
SELECT * FROM bloques WHERE 2 IN (roles)
and only find row_2, because it starts by 2
The LIKE option doesn't work because if I find 1
SELECT * FROM bloques WHERE roles LIKE '%1%'
, it gives me both rows.

FIND_IN_SET function cal helps you:
SELECT FIND_IN_SET('b','a,b,c,d');
For your code:
SELECT * FROM bloques WHERE FIND_IN_SET(2,roles);
Also, I suggesto to you that move your schema to 1NF

Could you use REGEXP? http://dev.mysql.com/doc/refman/5.1/en/regexp.html
Otherwise, you could add commas to the front and end of your rows.
select * from mytable where ',' + roles + ',' like '%,2,%'

SELECT
*
FROM
bloques
WHERE
roles LIKE '%,2,%'
OR roles LIKE '2,%'
OR roles LIKE '%,2'
The first case will give you all cases where 2 is in the middle of a set, the second case is when 2 starts the set, and the third case is when 2 ends the set. This is probably terribly inefficient, but it should work.

You can use this regex here:
SELECT * FROM bloques
WHERE roles REGEXP '[[:<:]]2[[:>:]]';
... or, in more generic case:
SELECT * FROM bloques
WHERE roles REGEXP CONCAT('[[:<:]]', :your_value, '[[:>:]]');
You need to use these weird-looking things, as they match word boundaries - preventing match for '2' to occur at '23' and '32'. )
The problem is that query is only the beginning of the troubles caused by using denormalized field. I'd suggest using either SET type (if the number of options is limited and low) or, way better, junction table to store the m-n relationships.

Use FIND_IN_SET() function
Try this:
SELECT * FROM bloques WHERE FIND_IN_SET(1, roles);
OR
SELECT * FROM bloques
WHERE CONCAT(',', roles, ',') LIKE '%,1,%';

Related

sql select where string matches pattern defined in another table

I have a select statement like this:
Select * from A where name like 'a%' or name like 'b%' or name like 'j%' or name like ... etc
Is it possible to store a%, b%, j% in a table somewhere so I can more easily manage this list and convert my query to something like:
Select * from A where name like (Select * from StringPatternToMatch)
Try this:
SELECT * FROM A
JOIN StringPatternToMatch patt ON A.name LIKE '%' + patt.pattern + '%';
Replace patt.pattern with the name of the column in your StringPatternToMatch
You can do a regexp search instead.
select *
from A where name regexp '^[abjf]';
It's easier query to maintain than a ton of or'd likes.
demo here
'^[abjf]' means match the start of the string (^), followed by any of the characters in the list ([abjf]). It doesn't care what comes after that.
Just add more letters to the list if you find names starting with them.

Query MySQL field for LIKE string

I have a field called 'areasCovered' in a MySQL database, which contains a string list of postcodes.
There are 2 rows that have similar data e.g:
Row 1: 'B*,PO*,WA*'
Row 2: 'BB*, SO*, DE*'
Note - The strings are not in any particular order and could change depending on the user
Now, if I was to use a query like:
SELECT * FROM technicians WHERE areasCovered LIKE '%B*%'
I'd like it to return JUST Row 1. However, it's returning Row 2 aswell, because of the BB* in the string.
How could I prevent it from doing this?
The key to using like in this case is to include delimiters, so you can look for delimited values:
SELECT *
FROM technicians
WHERE concat(', ', areasCovered, ', ') LIKE '%, B*, %'
In MySQL, you can also use find_in_set(), but the space can cause you problems so you need to get rid of it:
SELECT *
FROM technicians
WHERE find_in_set('B', replace(areasCovered, ', ', ',') > 0
Finally, though, you should not be storing these types of lists as strings. You should be storing them in a separate table, a junction table, with one row per technician and per area covered. That makes these types of queries easier to express and they have better performance.
You are searching wild cards at the start as well as end.
You need only at end.
SELECT * FROM technicians WHERE areasCovered LIKE 'B*%'
Reference:
Normally I hate REGEXP. But ho hum:
SELECT * FROM technicians
WHERE concat(",",replace(areasCovered,", ",",")) regexp ',B{1}\\*';
To explain a bit:
Get rid of the pesky space:
select replace("B*,PO*,WA*",", ",",");
Bolt a comma on the front
select concat(",",replace("B*,PO*,WA*",", ",","));
Use a REGEX to match "comma B once followed by an asterix":
select concat(",",replace("B*,PO*,WA*",", ",",")) regexp ',B{1}\\*';
I could not check it on my machine, but it's should work:
SELECT * FROM technicians WHERE areasCovered <> replace(areaCovered,',B*','whatever')
In case the 'B*' does not exist, the areasCovered will be equal to replace(areaCovered,',B*','whatever'), and it will reject that row.
In case the 'B*' exists, the areCovered will NOT be eqaul to replace(areaCovered,',B*','whatever'), and it will accept that row.
You can Do it the way Programming Student suggested
SELECT * FROM technicians WHERE areasCovered LIKE 'B*%'
Or you can also use limit on query
SELECT * FROM technicians WHERE areasCovered LIKE '%B*%' LIMIT 1
%B*% contains % on each side which makes it to return all the rows where value contains B* at any position of the text however your requirement is to find all the rows which contains values starting with B* so following query should do the work.
SELECT * FROM technicians WHERE areasCovered LIKE 'B*%'

how to restrict `like` operator in query to start with something

I want to write a query that title start with A or B
is this correct?
I dont want use OR
I want use it in mysql ,
select * from table where title like `[AB]%`
Use REGEXP instead of LIKE:
SELECT * FROM table
WHERE title REGEXP '^[AB]'
DEMO
Or just use a substring:
SELECT * FROM table
WHERE LEFT(title, 1) IN ('A', 'B');
you can do it like
select * from table where title like `A%` OR title like `B%`
another way is to use regular expression
select * from table where title REGEXP '^(A|B)';
This is correct way:
SELECT * FROM table WHERE title LIKE 'A%' or title LIKE 'B%';
What you wrote should work. or you can use,
select *
from table_name
where title LIKE 'A%' OR title LIKE 'B%'
Unfortunately, the LIKE operator in SQL only supports a limited syntax. It doesn't support a regex style syntax.
You have to do divide it into two expressions:
select * from table where (title like 'A%' or title like 'B%')
Note:
In this case the parenthesis are superfluous, but since OR has a lower precedence than AND I think it is good practice to routinely add parenthesis around ORexpressions in SQL.

MySQL Finding data using IN and LIKE Wildcard

How would I go about doing something like:
SELECT * FROM mytable
WHERE people IN ('Jack', '%Bob%')
Finding all fields that either equal 'Jack' or contain 'Bob'? I don't think my example is the proper syntax because it's not pulling up any records.
Simply :
SELECT * FROM mytable WHERE people='Jack' OR PEOPLE LIKE '%Bob%'

MySQL Like multiple values

I have this MySQL query.
I have database fields with this contents
sports,shopping,pool,pc,games
shopping,pool,pc,games
sports,pub,swimming, pool, pc, games
Why does this like query does not work?
I need the fields with either sports or pub or both?
SELECT * FROM table WHERE interests LIKE ('%sports%', '%pub%')
Faster way of doing this:
WHERE interests LIKE '%sports%' OR interests LIKE '%pub%'
is this:
WHERE interests REGEXP 'sports|pub'
Found this solution here: http://forums.mysql.com/read.php?10,392332,392950#msg-392950
More about REGEXP here: http://www.tutorialspoint.com/mysql/mysql-regexps.htm
The (a,b,c) list only works with in. For like, you have to use or:
WHERE interests LIKE '%sports%' OR interests LIKE '%pub%'
Why not you try REGEXP. Try it like this:
SELECT * FROM table WHERE interests REGEXP 'sports|pub'
You can also use REGEXP's synonym RLIKE as well.
For example:
SELECT *
FROM TABLE_NAME
WHERE COLNAME RLIKE 'REGEX1|REGEX2|REGEX3'
Don't forget to use parenthesis if you use this function after an AND parameter
Like this:
WHERE id=123 and(interests LIKE '%sports%' OR interests LIKE '%pub%')
Or if you need to match only the beginning of words:
WHERE interests LIKE 'sports%' OR interests LIKE 'pub%'
you can use the regexp caret matches:
WHERE interests REGEXP '^sports|^pub'
https://www.regular-expressions.info/anchors.html
Your query should be SELECT * FROM `table` WHERE find_in_set(interests, "sports,pub")>0
What I understand is that you store the interests in one field of your table, which is a misconception. You should definitively have an "interest" table.
Like #Alexis Dufrenoy proposed, the query could be:
SELECT * FROM `table` WHERE find_in_set('sports', interests)>0 OR find_in_set('pub', interests)>0
More information in the manual.
More work examples:
SELECT COUNT(email) as count FROM table1 t1
JOIN (
SELECT company_domains as emailext FROM table2 WHERE company = 'DELL'
) t2
ON t1.email LIKE CONCAT('%', emailext) WHERE t1.event='PC Global Conference';
Task was count participants at an event(s) with filter if email extension equal to multiple company domains.