Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using LEFT JOIN and LIKE mysql

Tags:

mysql

i have a problem in mysql query. this is how my tables looks like:

mysql> select username, specialty from users;
+----------+------------------+
| username | specialty        |
+----------+------------------+
| JinkX    | php, html, mysql |
| test1    | html             |
+----------+------------------+


mysql> select name, tags from tasks;
+----------------+------+
| name           | tags |
+----------------+------+
| fix front page | html |
+----------------+------+

and when i try to do the following query, it works only if the specialty equals exactly the tags. but i want it to work on both

mysql> select tasks.name from users left join tasks on tasks.tags LIKE users.specialty where users.username = 'test1';
+----------------+
| name           |
+----------------+
| fix front page |
+----------------+

mysql> select tasks.name from users left join tasks on tasks.tags LIKE users.specialty where users.username = 'JinkX';
+------+
| name |
+------+
| NULL |
+------+
like image 898
saadlulu Avatar asked Dec 03 '22 09:12

saadlulu


1 Answers

You're doing like wrong.

Try this query:

select tasks.name 
from users left join tasks on users.specialty LIKE CONCAT('%',tasks.tags,'%') 
where users.username = 'JinkX'

This is not the best way but it should work

EDIT: as per comments there's another way which should be better

Using REGEXP:

select tasks.name 
from users left join tasks on users.specialty REGEXP CONCAT('(^|,) ?',tasks.tags,' ?($|,)') 
where users.username = 'JinkX'
like image 136
Keeper Avatar answered Dec 11 '22 16:12

Keeper