Mysql SQL查询联接2个表,并显示两个表的列值相似的最终结果
我有两个带有条形码字符串的表,这两个表都有值 事务表Mysql SQL查询联接2个表,并显示两个表的列值相似的最终结果,mysql,sql,Mysql,Sql,我有两个带有条形码字符串的表,这两个表都有值 事务表 ID | Barcode | Date | From_Reject 1 Bar01 July 2020 2 Bar02 July 2020 Yes 3 Bar03 July 2020 拒绝表 Reject ID | Barcode | Reject Date | Status 1 Bar04 August
ID | Barcode | Date | From_Reject
1 Bar01 July 2020
2 Bar02 July 2020 Yes
3 Bar03 July 2020
拒绝表
Reject ID | Barcode | Reject Date | Status
1 Bar04 August 2020 Active
2 Bar02 September 2020 Reworked
3 Bar05 January 2020 Active
最终结果
ID | Reject ID | Barcode | Date | Reject Date | From_Reject | Status
1 null Bar01 July 2020 null null null
2 2 Bar02 July 2020 September 2020 YES REWORKED
3 null Bar03 July 2020 null null null
null 1 Bar04 null August 2020 null Active
null 3 Bar05 null January 2020 null Active
有没有可能我用左连接就可以实现呢?因为我尝试使用左连接或外连接,这两种连接都没有显示为我想要的最终结果。这是其他sql查询语法可以实现的吗?这个问题最初被标记为MySQL。这为MySQL和任何其他数据库提供了答案 基本上,您需要一个
完全连接
,MySQL不支持。我建议:
select *
from transactions t left join
rejects r
using (barcode)
union all
select *
from transactions t right join
rejects r
using (barcode)
where t.barcode is null;
请注意,此查询经过精心设计,使用了union all
,而不是union
。此外,右连接
非常有用,这是极少数情况之一。这允许使用*
,它将以相同的顺序为两个子查询返回该列
如果您有一个条形码列表
,那么我建议将其与左连接一起使用:
select *
from barcodes b left join
transactions t
using (barcode) left join
rejections r
using (barcode);
编辑:
在SQL Server(以及几乎任何其他数据库)中,您只需执行以下操作:
select *
from transactions t full join
rejects r
on t.barcode = r.barcode
两个数据库表上的所有表列都将显示为display right?@Marcus。对如果您想要一个子集,请明确列出它们。我还可以添加where子句,用于选择拒绝日期或从2020年8月开始的日期,对吗?我使用“使用”(条形码),但我的sql server显示不正确syntax@Marcus…如果您遇到SQL Server错误,则表明您错误地标记了该问题。请将标记更改为SQL Server。如果您对筛选结果有不同的问题,请使用适当的示例数据、说明和数据库标记提出新问题。