【问题标题】:Select union distinct records from two tables on the basis of common column根据公共列从两个表中选择联合不同的记录
【发布时间】:2020-05-06 23:16:11
【问题描述】:

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

Select * from Table1
union
Select * from Table2

表 1

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

表2

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

联合表

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

【问题讨论】:

  • SO 不是代码编写服务!当您遇到困难时,请尝试提出问题。
  • 感谢您的建议,但我正在使用 table1 unions table2 并没有得到正确的输出。你能帮帮我吗?
  • 直接向我们展示您的查询...
  • 我刚刚用我的查询更新了问题。
  • 如果您方便我,我会通过添加 DDL/DML 语句来看看。 Example of creating DDL/DML

标签: sql sql-server tsql join union


【解决方案1】:

尝试以下操作,这里是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   |
*------------------------------------------*

【讨论】:

  • 感谢您拯救了我的一天!实际表有 15M 条记录和大约 60 列具有此类条件。您的查询非常适合我。发现!再次感谢..
【解决方案2】:

我会在这里使用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 是语言关键字,因此不是列名的好选择。

【讨论】:

  • @JohnBristiw:让我指出这应该比union/not exists 解决方案更有效,因为它不涉及多个表扫描。
  • 你说得对,这种方法更快,因为它不涉及多表扫描。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 2011-10-31
相关资源
最近更新 更多