Senthil Kumar Senthil Kumar - 9 months ago 39
MySQL Question

How to SELECT values if id available in column(Comma separated values) using mysql?

How to SELECT values if id available in column(Comma separated values) using MySQL?

Here I need to get all values when the given id=17 available in

group_id
column.

Table:

+------------+---------------+
| user_id | group_id |
+------------+---------------+
| 1 | 1,2,3 |
| 3 | 12,23,17 |
| 5 | 17,26 |
+------------+---------------+


I try:

SELECT * FROM `group` WHERE units_id IN('17'); //No result


Expecting result:

+------------+---------------+
| user_id | group_id |
+------------+---------------+
| 3 | 12,23,17 |
| 5 | 17,26 |
+------------+---------------+

Answer

Try this one. You can use find_in_set :

SELECT * FROM `user` WHERE find_in_set('17',group_id) ORDER BY user_id;

RESULT:

+------------+---------------+
| user_id    | group_id      |
+------------+---------------+
|          3 |      12,23,17 |
|          5 |         17,26 |   
+------------+---------------+  

REF: MySQL query finding values in a comma separated string