SELECT WHERE IN (subquery) slow(SELECT WHERE IN(子查询)慢)
问题描述
我已经尝试了解决方案 这里,但它不起作用.
I've tried the solution here, but it doesn't work.
我的桌子是这样的:
`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.
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')
我之前没有使用 WHERE IN 的版本如下:
My previous version without using WHERE IN is as following:
首先检索所有带有 dept=dept1 的 uid.
然后对第一个查询中检索到的所有 uid 使用 for 循环.
Retrieves all the uid with dept=dept1 first.
Then use a for-loop for all uid retrieved in the first query.
对于在第一个查询中检索到的少量 (100) 行,此方法非常快.但是,这似乎不是一个好的解决方案,因为它会创建大量查询(每个查询都非常快).
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).
推荐答案
试试这个:
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
这篇关于SELECT WHERE IN(子查询)慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SELECT WHERE IN(子查询)慢
基础教程推荐
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
