Oracle SQL:使用空表加入

时间:2013-10-25 22:22:08

标签: sql oracle join

我说有3个表,其中有一个键可以链接所有三个表...

select a.call_id, b.name, c.year
from table1 a, table2 b, table3 c
where a.call_id = b.call_id
and b.call_id = c.call_id
and a.call_id = 123

问题是表3没有匹配id为123的记录,因此整个查询返回0行,即使表1和表1中存在匹配。 2.有没有办法我可以让oracle为c.year字段返回say null并仍然得到a.call_id和b.name的结果?

3 个答案:

答案 0 :(得分:2)

我想你只需将其转换为JOIN:

SELECT a.call_id, b.name, c.year
from table1 a
JOIN table2 b
ON a.call_id = b.call_id
LEFT JOIN table3 c
ON and b.call_id = c.call_id
WHERE a.call_id = 123

答案 1 :(得分:2)

是的,您必须使用LEFT加入:

select a.call_id, b.name, c.year
  from table1 a
    JOIN table2 b ON (a.call_id = b.call_id)
    LEFT JOIN table3 c ON (b.call_id = c.call_id)
  WHERE a.call_id = 123;

在此处详细了解联接:Visual Explanation of Joins by Jeff Atwood

答案 2 :(得分:1)

虽然您应该使用ANSI SQL,但您也可以使用(+)

进行Oracle方式
select a.call_id, b.name, c.year
from table1 a, table2 b, table3 c
where a.call_id = b.call_id
and b.call_id = c.call_id(+)
and a.call_id = 123