首页 文章

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

提问于
浏览
0

我有两张 table :

表格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

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

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 with Demo

相关问题