15

I have two tables: pq and pe. I am trying to LEFT OUTER JOIN left table (pq) on right table (pe).

  • pq has primary key column id
  • pe has two-column primary key, so it may have many pqid's or none
  • pe.uid column has to be used to extract only relevant data (WHERE pe.uid = "12345")
  • pe.data should be joined to every pq.id row

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

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:

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:

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

I need to get this:

pq.id | pq.data |  pe.data
1     | "abc"   |  
2     | "efg"   |  "xyz"
4

1 回答 1

43

是的。该where子句将左外连接变为内连接。

为什么?没有匹配项时的值为pe.pqid( NULLas is )。pe.uid因此where子句中的比较失败(几乎所有要NULL返回的比较NULL都被认为是错误的)。

解决方案是将比较移至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
于 2013-07-28T17:23:29.513 回答