简体   繁体   English

如何使用子查询优化“WHERE NOT IN”

[英]How to optimize “WHERE NOT IN” with subquery

I have this query what was discussion output in this thread: Mysql JOIN subquery 我有这个查询在这个线程中讨论输出的内容: Mysql JOIN子查询

See current fiddle: http://sqlfiddle.com/#!2/e97cf/22 查看当前的小提琴: http ://sqlfiddle.com/#!2 / e97cf / 22

create table c_contact 
(id INT, 
 name VARCHAR(20), 
 securityid INT
);

create table c_monitoring 
(started DATE, 
 ended DATE DEFAULT NULL, 
 securityid INT
);


SELECT
  c_contact.id,
  c_contact.name,
  c_contact.securityid
FROM c_contact
WHERE c_contact.securityid != ''
  AND c_contact.securityid NOT IN
      (select securityid 
       from c_monitoring 
       where ended is null 
       group by securityid
      )
GROUP BY c_contact.id ;

How the hell I am going to optimize this query? 我该如何优化这个查询呢? I have 100.000 records in c_contact table and about 10.000 in c_monitoring table. 我在c_contact表中有100.000条记录,在c_monitoring表中有大约10.000条记录。 Query takes > 30 secs with 127 result rows. 查询需要> 30秒,结果行数为127。

EDIT: Case was solved by indexing tables correctly. 编辑:案例通过正确索引表解决。

Your query has some group by problems (actually, you should not have any group by clauses), and you should convert it to a join: 您的查询有一些问题(实际上,您不应该有任何group by子句),您应该将其转换为连接:

SELECT
  c.id,
  c.name,
  c.securityid
FROM c_contact c
LEFT JOIN c_monitoring m ON m.securityid = c.securityid
  AND m.ended is null
WHERE c.securityid != ''
AND m.securityid IS NULL

See SQLFiddle 请参见SQLFiddle

I also tidied up the query a little with aliases. 我还用别名整理了一下查询。

Case was solved by indexing table fields 通过索引表字段解决了案例

  • c_contact.securityid c_contact.securityid
  • c_monitoring.started c_monitoring.started
  • c_monitoring.ended c_monitoring.ended
  • c_monitoring.securityid c_monitoring.securityid

Query takes now ~200ms 查询现在需要~200ms

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

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