views:

252

answers:

9

I have a php array of "primary key" values, which correspond to just a few rows of a very long table of data, saved on a MySql database. How can I fetch with just one query only those rows. Is it possible or will I need to make one query per primary key? eg: SELECT * FROM table1 WHERE key = 8573

Thanks, Patrick

+9  A: 

You can use MySQL's IN() operator.

... WHERE x in (1,4,9,16)
VolkerK
IN is a bit of a SQL silver bullet that too many coders don't use either because they don't know about it or forget it exists.
TravisO
+2  A: 
Select * from table1 WHERE key IN ([values separated by commas])
rosscj2533
+1  A: 

Two options:

select * from table1 where key in (8573, 5244, 39211);
select * from table1 where key = 8573 or key = 5244 or key = 39211;
nullptr
A: 

Just use this form of select

SELECT * FROM table1 WHERE key IN (1234, 1235, 6789, 9876)
Nick Craig-Wood
+4  A: 
Select * from table WHERE primary_key IN (8573,8574,8578)

for your php array you could use implode

$key_array = implode(",", $array);

Select * from table WHERE primary_key IN ($key_array)
mmundiff
A: 

Use php's implode function:

$keys = array(1,2,3,4);
$sql = "SELECT * FROM table WHERE key IN ( " . implode($keys, ",") . ")";
+2  A: 

On most databases, "key IN (set)" works faster than "key=a or key=b or...".

Specifically for PHP, you may use implode to generate your SQL:

$SQL = "select * from table where key in (".implode(',', $KeyArray)).")"

Assuming integer key. With a string key, you need to quote them:

$SQL = "select * from table where key in ('".implode("','", $KeyArray))."')"

Seva Alekseyev
+1  A: 

Use the OR statement.

SELECT * FROM table1 WHERE key=8573 OR key=9999;

Of course this can get really long, so you'll probably want to use a loop and concatenate the keys to the query string.

jonescb
+1  A: 
$query = "SELECT * FROM tableName WHERE primaryKey IN ('" . implode("','", $keys) . "')";
Jordan Ryan Moore