Sql 如果当前表中不存在行,请从其他表中选择行

Sql 如果当前表中不存在行,请从其他表中选择行,sql,sql-server-2008,Sql,Sql Server 2008,我有两张桌子: 表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 我需要从表1中选择所有行。但是,如果表2中存在表1中不存在的行,

我有两张桌子:

表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
我需要从表1中选择所有行。但是,如果表2中存在表1中不存在的行,我需要将其包括在结果集中。因此,最后,我的查询应该返回以下内容:

id   name       qty
1    Tedd       6
2    Jim        7
3    Sally      8
4    Victoria   1
5    Alex       9
我有办法做到这一点吗?谢谢。

您可以使用完全外部联接:

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