mysql - 加入查询但消除重复
问题描述
所以我有这些数据,来自 tbl_left :
id name type our_assets
1 'Mira' cc 10
2 'Mira' bb 9
而这个,来自 tbl_right :
id name assets_other name_of_assets
1 'Mira' 3 assets_a
2 'Mira' 1 assets_b
3 'Mira' 1 assets_c
4 'Mira' 1 assets_d
我怎样才能加入这两个表和结果是这样的:
name type our_assets assets_other name_of_assets
'Mira' cc 10 3 assets_a
'Mira' bb 9 1 assets_b
'Mira' 1 assets_c
'Mira' 1 assets_d
我不在乎列类型和 our_assets 是否有重复值,我尝试使用 join 但结果变为 8 行而不是 4 行,例如:
name type our_assets assets_other name_of_assets
'Mira' cc 10 3 assets_a
'Mira' cc 10 3 assets_a
'Mira' bb 9 1 assets_b
'Mira' bb 9 1 assets_b
'Mira' 1 assets_c
'Mira' 1 assets_c
'Mira' 1 assets_d
'Mira' 1 assets_d
如果我使用 group by name_of_assets 列类型仅返回“cc”值。
解决方案
您需要添加另一个连接条件,name
以避免重复记录。一种选择使用row_number()
(在 MySQL 8.0 中可用):
select r.name, l.type, l.our_assets, r.assets_other, r.name_of_asset
from (select r.*, row_number() over(partition by name order by id) rn from tbl_right) l
left join (select l.*, row_number() over(partition by name order by id) rn from tbl_left) r
on r.name = l.name and r.rn = l.rn
如果连接的两端可能缺少记录,您可以使用union all
和聚合来代替:
select
name,
max(type) type,
amx(our_assets) our_assets,
max(assets_other) assets_other,
max(name_of_asset) name_of_asset
from (
select
name,
type,
our_assets,
null assets_other,
null name_of_asset,
row_number() over(partition by name order by id) rn
from tbl_left
union all
select
name,
null,
null,
assets_other,
name_of_asset,
row_number() over(partition by name order by id) rn
from tbl_right
) t
group by name, rn
推荐阅读
- php - PHP FIle not found when i submit a form
- r - Transform tibble to data frame with column headers
- php - 将变量从一个 php 文件发送到另一个文件并在第三个文件中显示变量值
- javascript - AmCharts Serial Chart: Center-align label under the axis points
- random - 在 R 中使用混合 logit 模型进行预测
- javascript - 在 redux 操作中控制异步批处理请求
- java - 如何打印通过硒中的“selectByVisibleText”方法选择的所选选项的文本
- java - 在 Android 应用上显示我的 Twitter 页面时间线
- android - AppCompat theme for Leanback
- angular - ngx-datatable,触发列排序