tags:

views:

41

answers:

2

Ok, normally I know you would do something like this is you knew the array vals:

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

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

SELECT * WHERE 3 IN (ids) // Where ids is stored as 1,2,3

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

Thanks.

PHP + MySQL

+2  A: 

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 (' . array_map('intval', implode(',', $ids)) . ')';
VoteyDisciple
+1 for array_map('intval', ...). You could also use mysql_real_escape_string() instead of intval(), which would leave the integer validation to MySQL, but would require extra logic to quote the array elements.
Jordan
Thanks, but as I stated, I know the id and didn't need to search for rows based on a known set. The other way around as answered below.
Tomas
+1  A: 

Use the FIND_IN_SET function:

SELECT t.*
  FROM YOUR_TABLE t
 WHERE FIND_IN_SET(3, t.ids) > 0
OMG Ponies
You sir, are a star. I searched high and low for it and knew it had to be there. My instincts told me they should have used CONTAINS for this, but what do I know.
Tomas
@Tomas: Only MySQL has that function - any other database, you'd have to build something yourself.
OMG Ponies
I don't plan on switching... but that's definitely good to know.
Tomas