[英]sql gives no results because empty left join
So I have this query: 所以我有这个查询:
SELECT
AED.aId, CJ.*
FROM
AED
LEFT JOIN
Cronjob as CJ
ON CJ.aID = AED.aId
WHERE
AED.aStatus = '1'
AND
(
CJ.cjDatum < CURRENT_DATE - INTERVAL 14 DAY
AND
AED.aRegistratie > CURRENT_DATE - INTERVAL 10 YEAR
)
OR
(
CJ.cjStatus = '9'
OR
CJ.cjStatus = '2'
)
The problem is, the Cronjob table is empty, and if it's empty is still want to give all the Id's from AED with the status 1 问题是,Cronjob表为空,并且如果它为空,仍要提供状态为1的AED的所有ID。
I couldn't find anything use full, so I hope you guys can help! 我找不到所有可用的东西,所以希望你们能帮忙!
You should move all the CJ criteria into the join's ON clause. 您应该将所有CJ条件移到联接的ON子句中。
ON (
CJ.aID = AED.aId
AND (cjStatus in ('2','9') OR cjDatum < CURRENT_DATE - INTERVAL 14 DAY ))
Option two would be to leave them in WHERE, but make provisions for the case that cjStatus and friends are NULL (which they will be if no match is found). 第二种选择是将它们留在WHERE中,但要为cjStatus和friends为NULL(如果未找到匹配项,则为NULL)的情况做出规定。
OR cjStatus IS NULL
When there is no CronJob associated, the filter CJ.cjStatus = '9'
(for example) return false, since CJ.cjStatus
is null. 当没有关联的CronJob时,过滤器CJ.cjStatus = '9'
(例如)返回false,因为CJ.cjStatus
为null。 That's what a LEFT JOIN do, it returns null field when there is no correspondance. 这就是LEFT JOIN的作用,当没有对应关系时,它将返回null字段。
To add filter on the table you want to LEFT JOIN with, the filter clause must be in the join clauses like this: 要在要进行LEFT JOIN处理的表上添加过滤器,filter子句必须位于如下的join子句中:
SELECT AED.aId
, CJ.*
FROM AED
LEFT JOIN Cronjob as CJ
ON CJ.aID = AED.aId
AND (CJ.cjDatum < CURRENT_DATE - INTERVAL 14 DAY
AND AED.aRegistratie > CURRENT_DATE - INTERVAL 10 YEAR
)
OR (CJ.cjStatus = '9' OR CJ.cjStatus = '2')
WHERE AED.aStatus = '1'
Add OR (CJ.aid is null)
to your AND part of condition: 将OR (CJ.aid is null)
添加到条件的AND部分:
SELECT
AED.aId, CJ.*
FROM
AED
LEFT JOIN
Cronjob as CJ
ON CJ.aID = AED.aId
WHERE
AED.aStatus = '1'
AND
(
(
CJ.cjDatum < CURRENT_DATE - INTERVAL 14 DAY
AND
AED.aRegistratie > CURRENT_DATE - INTERVAL 10 YEAR
)
OR (CJ.aid is null)
)
OR
(
CJ.cjStatus = '9'
OR
CJ.cjStatus = '2'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.