如何用JOIN替换NOT EXISTS嵌套选择

时间:2010-09-22 10:47:48

标签: mysql query-optimization

嘿那里,我有点试图优化在嵌套SELECT上有NOT EXISTS子句的查询。我一直在重写包含嵌套选择的查询,将它们更改为连接,但在这种情况下,我不确定如何将它与NOT EXISTS子句结合起来。我有以下查询:

SELECT `reg_no`, COUNT(*) AS `records_found` 
FROM (`club_records` AS `cr`) 
WHERE NOT EXISTS ( 
  SELECT `number` FROM `members` WHERE `members`.`number` = `cr`.`alt_reg_no` 
)

1 个答案:

答案 0 :(得分:4)

http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/

SELECT `reg_no`, COUNT(*) AS `records_found`,members`.`number`
FROM `club_records` AS `cr`
LEFT OUTER JOIN members`
ON  `members`.`number` = `cr`.`alt_reg_no
WHERE members`.`number` IS NULL;

注意: 成员编号定义必须包含NOT NULL约束