简体   繁体   English

MySQL使用where子句保留外连接 - 返回不匹配的行

[英]MySQL left outer join with where clause - return unmatched rows

I have two tables: pq and pe . 我有两张桌子: pqpe I am trying to LEFT OUTER JOIN left table ( pq ) on right table ( pe ). 我想LEFT OUTER JOIN留在右表(PE)(PQ)。

  • pq has primary key column id pq具有主键列id
  • pe has two-column primary key, so it may have many pqid's or none pe有两列主键,所以它可能有很多pqid或者没有
  • pe .uid column has to be used to extract only relevant data ( WHERE pe.uid = "12345" ) pe .uid列必须用于仅提取相关数据( WHERE pe.uid = "12345"
  • pe .data should be joined to every pq .id row pe .data应该连接到每个pq .id行

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM