Select 根据公共列合并两个表中的不同记录

Select union distinct records from two tables on the basis of common column

我想合并 Table1 和 Table2 以及 select 不同的记录。如果两个表中的 Transaction_id 相同,我想要来自 Table1 的记录(根本不是来自 Table2 的记录)。有人可以为我写一个 SQL 服务器查询吗? 我正在尝试下面的查询,但我得到了重复的记录。

Select * from Table1
union
Select * from Table2

Table1

Transaction_id  Product Quantity    Return
     1           Pen       2       No DATA
     2           pencil    4       No DATA
     3           sharpner  6       No DATA
     4           eraser    10      No DATA

Table2

Transaction_id  Product Quantity    Return
     3           sharpner   6       Yes
     5           Book       9       Yes

联盟Table

Transaction_id  Product Quantity    Return
     1           Pen       2       No DATA
     2           pencil    4       No DATA
     3           sharpner  6       No DATA
     4           eraser    10      No DATA
     5           Book      9       Yes

尝试以下操作,这是 demo

select
  transaction_id,
  product,
  quantity,
  retur
from table1

union all

select
  transaction_id,
  product,
  quantity,
  retur
from table2 t2
where not exists (
  select
    transaction_id
  from table1 t1
  where t2.transaction_id = t1.transaction_id
)

输出:

*------------------------------------------*
|transaction_id  product quantity   retur  |
*------------------------------------------*
|  1               Pen        2     No DATA|
|  2               pencil     4     No DATA|
|  3               sharpner   6     No DATA|
|  4               eraser     10    No DATA|
|  5               book       9      yes   |
*------------------------------------------*

我会在这里使用 full join 和条件逻辑:

select
    coalesce(t1.transaction_id, t2.transaction_id)transaction_id,
    case when t1.transaction_id is not null then t1.product else t2.product end product,
    case when t1.transaction_id is not null then t1.quantity else t2.quantity end quantity,
    case when t1.transaction_id is not null then t1.return else t2.return end return
from table1 t1
full join table2 t2 on t1.transaction_id = t2.transaction_id

请注意 return 是语言关键字,因此不是列名的好选择。