简体   繁体   English

从具有百万条目的mysql数据库中获取少量记录

[英]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. 它将用户ID作为主键。 I have an array having 500 user ids in it. 我有一个包含500个用户ID的数组。

I want to select all the records from the table whose user ids are in the array. 我想从表中选择用户ID在数组中的所有记录。 I know one method to do this is to change the array into a string and run IN query by passing the string. 我知道一种方法是将数组更改为字符串并通过传递字符串来运行IN查询。

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. 我假设你的id是整数。 Maybe you are getting this list of Ids from some other sources so that a join on mysql side is not desired solution. 也许你从其他一些来源获得这个ID列表,以便在mysql端加入不是所需的解决方案。 If yes, then find the maximum and minimum id present in your 500 Ids list. 如果是,则查找500 Ids列表中的最大和最小ID。 You can do this in php side. 你可以在php端做到这一点。 When you have the max and min value, then query mysql db with a where clause 当你有max和min值时,用一个where clause查询mysql db

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. id是主键,因此优点是它已经被索引。

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 ... 我用ids创建一个字符串:其中id = a或id = b或id = c ...

then I add the select statement in front of it, and do a fetchall. 然后我在它前面添加select语句,然后做一个fetchall。

My guess is that you're getting these user IDs from another table and that you are storing them in an array. 我的猜测是你从另一个表中获取这些用户ID,并将它们存储在一个数组中。 If this is correct, then you should change the query that fetches these user IDs so that it uses a join instead. 如果这是正确的,那么您应该更改获取这些用户ID的查询,以便它使用连接。

Joins will help you there, because IN() is not a good programming practice. 联接将帮助你,因为IN()不是一个好的编程实践。 You can learn about joins here : http://mysqljoin.com/ 您可以在这里了解加入http//mysqljoin.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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