[英]MySQL left outer join with where clause - return unmatched rows
I have two tables: pq and pe . 我有两张桌子: pq和pe 。 I am trying to
LEFT OUTER JOIN
left table ( pq ) on right table ( pe ). 我想
LEFT OUTER JOIN
留在右表(PE)表(PQ)。
WHERE pe.uid = "12345"
) WHERE pe.uid = "12345"
) Here is how tables look: 表格如下:
pq:
id | data
1 | "abc"
2 | "efg"
pe:
pqid | uid | data
2 | 54321 | "uvw"
2 | 12345 | "xyz"
I can use the following query to match first 2 rows of pq .id to pe .pqid 我可以使用以下查询将pq .id的前2行与pe .pqid进行匹配
SELECT pq.id, pq.data, pe.data FROM pq
LEFT OUTER JOIN pe ON pq.id = pe.pqid
ORDER BY pq.id LIMIT 2
I get: 我明白了:
pq.id | pq.data | pe.data
1 | "abc" |
2 | "efg" | "uvw"
But if I use the WHERE statement like this: 但是如果我像这样使用WHERE语句:
SELECT pq.id, pq.data, pe.data FROM pq
LEFT OUTER JOIN pe ON pq.id = pe.pqid
WHERE pe.uid='12345'
ORDER BY pq.id LIMIT 2
I only get one row with matching pe .pqid AND pe .uid: 我只得到一行匹配pe .pqid AND pe .uid:
pq.id | pq.data | pe.data
2 | "efg" | "xyz"
So with the WHERE clause I get the right pe .data, but I don't get pq rows that have no pq .id matching pe .pqid 所以使用WHERE子句我得到了正确的pe .data,但我没有得到没有匹配pe .pqid的pq .id的pq行
I need to get this: 我需要得到这个:
pq.id | pq.data | pe.data
1 | "abc" |
2 | "efg" | "xyz"
Yes. 是。 The
where
clause is turning the left outer join into an inner join. where
子句将左外连接转换为内连接。
Why? 为什么? The value of
pe.pqid
is NULL
(as is pe.uid
) when there is no match. 当没有匹配时,
pe.pqid
值为NULL
(如pe.uid
)。 So the comparison in the where
clause fails (almost all comparisons to NULL
return NULL
which is considered false). 所以
where
子句中的比较失败(几乎所有与NULL
比较都返回NULL
,这被认为是假的)。
The solution is to move the comparison to the on
clause: 解决方案是将比较移动到
on
子句:
SELECT pq.id, pq.data, pe.data
FROM pq LEFT OUTER JOIN
pe
ON pq.id = pe.pqid and
pe.uid='12345'
ORDER BY pq.id LIMIT 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.