左外连接不适用于具有重复ID的列

时间:2014-08-11 18:27:36

标签: mysql sql

这是 table1

enter image description here

这是 table2

enter image description here

我想看到这个结果:

enter image description here

我写了这个查询:

select title, value 
from table1 
left outer join table2 
    on table1.id = table2.id 
where category="good"

但它给了我这个结果:

enter image description here

那么,我应该使用什么查询来获得带有标题c的结果""? (空字符串)

3 个答案:

答案 0 :(得分:2)

这应该有效:

select title, value
from table1 
left outer join table2
on table1.id = table2.id and category="good"

and category="good"安排到on子句。不是where子句。

答案 1 :(得分:2)

使用left outer join时,需要在on子句中的 second 表中添加条件。如果将条件放在where子句中,则通常会失败,因为不匹配的行将具有NULL值。

第一个表的条件应该放在where子句中。所以试试这个:

select title, value
from table1 left outer join
     table2
      on table1.id = table2.id and category = 'good';

答案 2 :(得分:2)

table2.category上的谓词移至ON子句,而不是WHERE子句。

(在WHERE子句中,它否定了LEFT JOIN操作的“外部性”,因为table1中没有与table2匹配的行的任何行对于table2列都将具有NULL值。检查非null值排除所有“不匹配”行,使LEFT JOIN等效于INNER JOIN

返回指定结果集的一种方法:

SELECT t.title
     , s.value
  FROM table1 t
  LEFT
  JOIN table2 s 
    ON s.id = t.id 
   AND s.category = "good"