选择具有相同列的2表而不加入

时间:2017-07-02 11:23:21

标签: sql sql-server select sql-server-2016

我有2张这样的表

loaded
fatal error: unexpectedly found nil while unwrapping an Optional value

---------tbl1----------------
id  | name   | lname |
1      j          h
2      jj         hh  

我想从这个2表中选择:

---------tbl2----------------
_id  | name   | lname |
1        a         b
2        aa        bb
3        aaa       ccc

但是选择使用加入结果不是这种格式!如何访问此选择结果?

1 个答案:

答案 0 :(得分:3)

您基本上在寻找union all

select row_number() over (order by which, id) as resultid,
       id, name, lname
from ((select id, name, lname, 1 as which from tbl1
      ) union all
      (select _id, name, lname, 2 as which from tbl2
      )
     ) n
order by which, id;

唯一棘手的部分是使用row_number()分配最终resultid