简体   繁体   中英

Fetching few records from mysql database having million entries

I have a table which has million rows. It has user id as its primary key. I have an array having 500 user ids in it.

I want to select all the records from the table whose user ids are in the array. I know one method to do this is to change the array into a string and run IN query by passing the string.

But I think it is not the efficient way to do it. So kindly suggest other ways.

I am assuming that your ids are integer. Maybe you are getting this list of Ids from some other sources so that a join on mysql side is not desired solution. If yes, then find the maximum and minimum id present in your 500 Ids list. You can do this in php side. When you have the max and min value, then query mysql db with a where clause

select ...
  from table_name
  where min_id <= id and id <= max_id

id is the primary key so the advantage is that it is already indexed.

I have done this in the past, I am not sure that my method is the most efficient.

I create a string out of the ids: where id = a or id = b or id = c ...

then I add the select statement in front of it, and do a fetchall.

My guess is that you're getting these user IDs from another table and that you are storing them in an array. If this is correct, then you should change the query that fetches these user IDs so that it uses a join instead.

Joins will help you there, because IN() is not a good programming practice. You can learn about joins here : http://mysqljoin.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM