Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - How to select rows where value is in array?

Tags:

php

mysql

Ok, normally I know you would do something like this if you knew the array values (1,2,3 in this case):

SELECT * WHERE id IN (1,2,3) 

But I don't know the array value, I just know the value I want to find is 'stored' in the array:

SELECT * WHERE 3 IN (ids) // Where 'ids' is an array of values 1,2,3 

Which doesn't work. Is there another way to do this?

like image 319
Tomas Avatar asked Oct 27 '10 19:10

Tomas


2 Answers

Use the FIND_IN_SET function:

SELECT t.*   FROM YOUR_TABLE t  WHERE FIND_IN_SET(3, t.ids) > 0 
like image 104
OMG Ponies Avatar answered Sep 30 '22 05:09

OMG Ponies


By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:

$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')'; 

If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:

$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')'; 
like image 36
VoteyDisciple Avatar answered Sep 30 '22 06:09

VoteyDisciple