What's the best way to get a bunch of rows from MySQL if you have an array of integer primary keys?

Posted by Evan P. on Stack Overflow See other posts from Stack Overflow or by Evan P.
Published on 2012-06-19T01:42:40Z Indexed on 2012/06/19 21:16 UTC
Read the original article Hit count: 192

Filed under:
|
|
|

I have a MySQL table with an auto-incremented integer primary key. I want to get a bunch of rows from the table based on an array of integers I have in memory in my program. The array ranges from a handful to about 1000 items.

What's the most efficient query syntax to get the rows?

I can think of a few:

  1. "SELECT * FROM thetable WHERE id IN (1, 2, 3, 4, 5)" (this is what I do now)
  2. "SELECT * FROM thetable where id = 1 OR id = 2 OR id = 3"
  3. Multiple queries of the form "SELECT * FROM thetable WHERE id = 1". Probably the most friendly to the query cache, but expensive due to having lots of query parsing.
  4. A union, like "SELECT * FROM thetable WHERE id = 1 UNION SELECT * FROM thetable WHERE id = 2 ..." I'm not sure if MySQL caches the results of each query; it's also the most verbose format.

I think using the NoSQL interface in MySQL 5.6+ would be the most efficient way to do this, but I'm not yet up to MySQL 5.6.

© Stack Overflow or respective owner

Related posts about mysql

Related posts about query