简体   繁体   English

MySQL - IN()函数是否需要完整的TABLE扫描?

[英]MySQL - Does IN() function require full TABLE scan?

Hey Guys, I am doing a social networking site that requires a good bit of queries. 嘿伙计们,我正在做一个需要大量查询的社交网站。 I am using 1 query that has a IN() function in it. 我正在使用1个具有IN()函数的查询。 I am wondering if this requires a full DB scan. 我想知道这是否需要完整的数据库扫描。 I am not sure of any other way to get the same results. 我不确定是否有任何其他方法可以得到相同的结果。

Example Table: 示例表:

ID | NAME | AGE
05 | Quinton | 25
22 | Stevey | 33
78 | Rebecca | 22
90 | Michael | 26

Query: "SELECT * FROM users WHERE id IN(05,78) ORDER BY id DESC LIMIT 0,2"

Is this the most efficient way to get a list of users that are in a array? 这是获取阵列中用户列表的最有效方法吗? (using PHP) (使用PHP)

In general IN does not need a table scan. 通常,IN不需要表扫描。 If you have an index on the id column MySQL will be able to use that index. 如果你在id列上有一个索引,那么MySQL将能够使用该索引。 But when you have only 4 rows in your table it is usually fastest to perform a table scan so when testing on a small amount of data you may find that the index is not being used until you insert more data. 但是当表中只有4行时,执行表扫描通常最快,因此在测试少量数据时,您可能会发现在插入更多数据之前不会使用索引。

It shouldn't require a db scan if you have an index on the ID field. 如果您在ID字段上有索引,则不应要求进行数据库扫描。 I am assuming that the ID field is the primary key which would mean it is indexed by default. 我假设ID字段是主键,这意味着它默认被索引。

You can check if an additional WHERE statement speeds things up. 您可以检查其他WHERE语句是否可以加快速度。 As they are evaluated from right to left a limitation to the lowest/highest id might be beneficial eg 当从右到左评估它们时,对最低/最高id的限制可能是有益的,例如

SELECT * FROM users WHERE id in(13,18,3456) AND id >= 13 AND id <= 3456

(presuming column id is indexed) (假设列id被索引)

First of all there is error in Query, it should be 首先,Query中存在错误,应该是

"SELECT * FROM users WHERE id IN(05,78) ORDER BY id DESC LIMIT 0,2"

Second thing, when ur using limit 0,2 then why u scan a full table, u can search like this 第二件事,当你使用limit 0,2然后为什么你扫描一个完整的表,你可以像这样搜索

WHERE id=05 OR id=78 ORDER BY RAND () LIMIT 2

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

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