This question already has an answer here:
I have the table like this:
+-------+-----------+
| name | ids |
+-------+-----------+
| Artur | 1, 2, 3 |
+-------+-----------+
| David | 11, 22, 33|
+-------+-----------+
I have the SQL query like this:
SELECT * FROM table WHERE ids LIKE '%$id%'
for exemple If $id=1;
I need the row of Artur to be retrieved .. The code works, but in this case ($id=1) the row of David also is retrieved, because his ids
containes the value of the variable $id.
So I need the SQL like: SELECT * FROM table WHERE "some number of ids"=$id
Or I have to use aproach of LIKE
with some other conditions?
Thanks in advance for the attention
</div>
You can use find_in_set()
select * FROM table WHERE find_in_set('1',ids) > 0 ;
Note that you are doing a poor db design and likely to have many problem in future. You should never store comma separated data. So the first step would be do a normalization.
Use find_in_set:
SELECT * FROM table WHERE find_in_set($id, ids)
But it is much more better to normalize your table.
Use mysql FIND_IN_SET.
SELECT * FROM table WHERE FIND_IN_SET($id, ids)
OR LIKE
SELECT * FROM table WHERE CONCAT(', ', ids, ', ') LIKE '%, $id ,'
But both are not recommended. You should normalize your database.