0

我有两张桌子:

表格1

id   name       qty
1    Tedd       6
2    Jim        7
3    Sally      8
4    Victoria   1

表2

id   name       qty
1    Tedd       2
2    Jim        2
3    Sally      2
4    Victoria   1
5    Alex       9

我需要从 Table1 中选择所有行。但是,如果 Table2 中存在 Table1 中不存在的行,我需要将其包含在结果集中。所以,最后,我的查询应该返回这个:

id   name       qty
1    Tedd       6
2    Jim        7
3    Sally      8
4    Victoria   1
5    Alex       9

有没有办法我可以做到这一点?谢谢。

4

1 回答 1

2

您可以使用FULL OUTER JOIN

select 
  coalesce(t1.id, t2.id) id,
  coalesce(t1.name, t2.name) name,
  coalesce(t1.qty, t2.id) qty
from table1 t1
full outer join table2 t2
  on t1.id = t2.id

请参阅带有演示的 SQL Fiddle

于 2013-03-15T18:52:34.410 回答