【问题标题】:Select Row from Other Table if Doesn't Exist in Current Table如果当前表中不存在,则从其他表中选择行
【发布时间】:2013-03-15 18:48:59
【问题描述】:

我有两张桌子:

表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

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

【问题讨论】:

    标签: sql sql-server-2008


    【解决方案1】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-12
      • 2013-10-22
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      相关资源
      最近更新 更多