从两个表中获取所有记录的唯一通用记录?

时间:2013-12-05 15:41:55

标签: sql sql-server-2008 join union right-join

嗨我有两个表结构就像这样

表1

 Customer   Company   price    qty     item        invno
   1          a        89       8      item1        23 
   2          b        80       4      item2        22
   3          c        90       3      item1        45
   4          d        19       6      item3        12

表2

 Customer   Company   price    qty     item       invno
   1          a        89       8      item1        23
   2          b        80       4      item2        18
   3          c        90       3      item1        45
   4          d        19       6      item3        15

基本上table1包含当前记录和table2当前+过去的记录,它们都有其他列

我想要的是获取table1和table2的所有记录但是在invno重复的情况下我需要来自table1的记录,在这种情况下,resultset将包含invno-23(table1),22(table1), 45(表1),12(表1),18(表2),15(表2)

我尝试使用UNION但它在不同的列选择上给出了不同的结果我坚持在这里任何帮助都会很棒。

2 个答案:

答案 0 :(得分:0)

SELECT t2.Customer,
  t2.Company,
  t2.price,
  t2.qty,
  t2.item,
  IFNULL(t1.invno,t2.invno)
FROM table2      AS t2
LEFT JOIN table1 AS t1
ON t2.Customer=t1.Customer

答案 1 :(得分:0)

以下是一种方法,使用union all和过滤器:

select *
from table1 t1
union all
select *
from table2 t2
where not exists (select *
                  from table1 t1
                  where t1.invno = t2.invno
                 );
相关问题