我在查询中有一个简单的连接但是我需要在两个表上都有条件“confirmed ='yes'”但是如果其中一个表没有任何匹配,则查询返回没有行。
数据库:
.----------parties----------.
| id - party_id - confirmed |
|---------------------------|
| 1 1 yes |
| 1 2 no |
| 1 3 no |
+---------------------------+
.-----------events----------.
| id - event_id - confirmed |
|---------------------------|
| 1 1 no |
+---------------------------+
或
.----------parties----------.
| id - party_id - confirmed |
|---------------------------|
| 1 1 no |
| 1 2 no |
| 1 3 no |
+---------------------------+
.-----------events----------.
| id - event_id - confirmed |
|---------------------------|
| 1 1 yes |
+---------------------------+
查询:
SELECT p.party_id, e.event_id
FROM parties p
LEFT JOIN events e
ON p.id=e.id
WHERE p.id = '1'
AND p.party_id IN (1,2,3)
AND e.event_id IN (1)
AND p.confirmed='yes'
AND e.confirmed='yes'
它只返回任何内容,但我希望它返回party_id 1,其中包含空的event_id或event_id以及空的party_id。我希望这是有道理的,我不会遗漏任何东西,谢谢你的帮助!
编辑添加了我需要返回event_id的反向数据库代码和一个空的party_id
答案 0 :(得分:2)
您的WHERE
条件会过滤掉NULLs
生成的所有LEFT JOIN
。
将涉及events
的所有条件移至ON
子句:
SELECT p.party_id, e.event_id
FROM parties p
LEFT JOIN
events e
ON e.id = p.id
AND e.event_id IN (1)
AND e.confirmed = 'yes'
WHERE p.id = '1'
AND p.party_id IN (1, 2, 3)
AND p.confirmed = 'yes'
UNION ALL
SELECT p.party_id, e.event_id
FROM events e
LEFT JOIN
parties p
ON p.id = e.id
AND p.party_id IN (1, 2, 3)
AND p.confirmed = 'yes'
WHERE e.event_id IN (1)
AND e.confirmed = 'yes'
AND p.id IS NULL