sql-帮助将子查询转换为具有联接的查询
作者:互联网
我陷入了联接查询.客户端站点正在运行mysql4,因此不能选择子查询.我使用联接重写的尝试进行得不太顺利.
我需要选择承包商表中列出的所有不在给定标签ID&县ID.但是,它们可能会列在
contractors2label,以及其他标签和县ID.
表:承包商
cID (primary, autonumber)
company (varchar)
…etc…
表:contractors2label
cID
labelID
countyID
psID
此查询与子查询一起工作:
SELECT company, contractors.cID
FROM contractors
WHERE contractors.complete = 1
AND contractors.archived = 0
AND contractors.cID NOT IN (
SELECT contractors2label.cID FROM contractors2label
WHERE labelID <> 1 AND countyID <> 1
)
我认为带有联接的查询将是等效的,但它不会返回任何结果.手动扫描数据显示我应该得到34行,这是上面的子查询返回的结果.
SELECT company, contractors.cID
FROM contractors
LEFT OUTER JOIN contractors2label ON contractors.cID = contractors2label.cID
WHERE contractors.complete = 1
AND contractors.archived = 0
AND contractors2label.labelID <> 1
AND contractors2label.countyID <> 1
AND contractors2label.cID IS NULL
解决方法:
进行LEFT JOIN时,需要将JOIN的所有条件放入ON子句中.
在您的示例中,对于不存在的左连接列,您将得到NULL,但是您随后将它们再次与无效的值(<> 1)进行比较.
SELECT c.company, c.cID
FROM contractors c
LEFT JOIN contractors2label c2
ON ( c2.cID = c.cID AND c2.labelID <> 1 AND c2.countyID <> 1 )
WHERE c.complete = 1
AND c.archived = 0
AND c2.cID IS NULL
顺便说一句:使用别名(例如我的示例中的c)使读取和写入查询更加容易.
标签:left-join,sql,mysql 来源: https://codeday.me/bug/20191106/2000862.html