0

I have this query what was discussion output in this thread: Mysql JOIN subquery

See current fiddle: 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. Query takes > 30 secs with 127 result rows.

EDIT: Case was solved by indexing tables correctly.

4

2 回答 2

2

您的查询有一些 group by 问题(实际上,您不应该有任何 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

请参阅SQLFiddle

我还用别名稍微整理了查询。

于 2014-01-14T10:29:19.113 回答
0

通过索引表字段解决了案例

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

查询现在需要约 200 毫秒

于 2014-01-14T10:53:41.013 回答