SELECT WHERE IN (subquery) slow

房东的猫 提交于 2019-12-06 15:38:17

问题


I've tried the solution here, but it doesn't work.

My table is like this:

   `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

I want to retrieve all the rows with a particular dept. That is, If I want to retrieve dept1, I want to retrieve all rows except uid=002, since there's no dept1 for uid=002.

The query string is slow even when using index:

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

My previous version without using WHERE IN is as following:

Retrieves all the uid with dept=dept1 first.
Then use a for-loop for all uid retrieved in the first query.

This method is very fast for a small amount(100) of rows retrieved in the first query. However, it seems that it's not a good solution because it creates a lot of queries(each of them is extremely fast).


回答1:


Try this one:

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

Demo: http://sqlfiddle.com/#!2/05774/4



来源:https://stackoverflow.com/questions/10023117/select-where-in-subquery-slow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!