1

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

1
  • Don't forget to add an index for your table. Running a query on a "long table of data" is expensive. Considere adding this: alter table table1 add index (key) Commented Dec 17, 2009 at 20:54

9 Answers 9

9

You can use MySQL's IN() operator.

... WHERE x in (1,4,9,16)
Sign up to request clarification or add additional context in comments.

1 Comment

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.
4
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)

Comments

2
Select * from table1 WHERE key IN ([values separated by commas])

Comments

2

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))."')"

Comments

1

Two options:

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

Comments

1

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.

Comments

1
$query = "SELECT * FROM tableName WHERE primaryKey IN ('" . implode("','", $keys) . "')";

Comments

0

Just use this form of select

SELECT * FROM table1 WHERE key IN (1234, 1235, 6789, 9876)

Comments

0

Use php's implode function:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.