2012-04-05 90 views
0

我试过解决方案here,但它不起作用。选择哪里在(子查询)慢

我的表是这样的:

`Index` uid dept 
........................... 
     1 001 dept1 
     2 001 dept2 
     3 001 dept3 
     4 002 dept2 
     5 002 dept3 
     6 002 dept4 
     7 003 dept1 
     8 003 dept5 
     9 004 dept1 
     10 004 dept6 

我想检索所有与特定dept行。也就是说,如果我想检索dept1,我想检索除uid = 002之外的所有行,因为对于uid = 002没有dept1

SELECT id FROM table WHERE uid IN 
(SELECT uid WHERE dept='dept1') 

我以前的版本,而无需使用WHERE IN是如下:使用索引,即使

查询字符串很慢

首先检索所有与部门= DEPT1的UID。
然后对第一个查询中检索到的所有uid使用for-loop。

该方法对于第一个查询中检索到的少量(100)行非常快。然而,它似乎并不是一个好的解决方案,因为它会产生很多查询(它们中的每一个都非常快)。

+0

感谢编辑。 – benck 2012-04-05 16:46:40

+0

This is similar with this http://stackoverflow.com/questions/6135376/mysql-select-where-field-in-subquery-extremely-slow-why – 2014-09-25 03:59:19

回答

8

试试这个:

select a.id from Table1 a 
inner join Table1 b on a.uid = b.uid and b.dept = 'dept1'; 

演示:http://sqlfiddle.com/#!2/05774/4

+0

[什么时候是'IN(SELECT ...)'performance有待改进?](http://datacharmer.blogspot.com/2008/09/drizzling-mysql.html) – 2012-04-05 06:14:19

+1

好消息:[MariaDB 5.3](http://kb.askmonty.org/en/what- is-mariadb-53)已经是一个稳定的版本。和MySQL 5.6(不稳定,但很快我认为)将有这些或类似的改进。 – 2012-04-05 06:16:48

+0

感谢您的链接:) – 2012-04-05 06:37:27