如何在MySQL中合并表

uqdfh47h  于 2022-12-17  发布在  Mysql
关注(0)|答案(1)|浏览(126)

表一
| S.NO | Package 盒|
| - ------|- ------|
| 1个|篮1|
| 第二章|篮2|
| 三个|篮3|
表二
| 水果盒|水果|
| - ------|- ------|
| 篮1|芒果|
| 篮1|苹果|
| 篮1|葡萄|
| 篮1|香蕉|
| 篮2|香蕉|
| 篮2|苹果|
表三
| 蔬菜盒|蔬菜|
| - ------|- ------|
| 篮1|番茄|
| 篮1|马铃薯|
| 篮2| cucumber |
| 篮2|马铃薯|
| 篮3|番茄|
获取输出为
| S.NO | Package 盒|水果|蔬菜|
| - ------|- ------|- ------|- ------|
| 1个|篮1|芒果|番茄|
| 1个|篮1|苹果|马铃薯|
| 1个|篮1|葡萄|番茄|
| 1个|篮1|香蕉|马铃薯|
如果我们在蔬菜列下检查篮子1,它再次重复相同的值,它应该是NULL。
先谢了!
需要以下输出表
| S.NO | Package 盒|水果|蔬菜类|
| - ------|- ------|- ------|- ------|
| 1个|篮1|芒果|番茄|
| 1个|篮1|苹果|马铃薯|
| 1个|篮1|葡萄|无效|
| 1个|篮1|香蕉|无效|

bxgwgixi

bxgwgixi1#

例如,使用row_number窗口函数,您可以导出要连接的行号

with 
cte1 as
(select S_NO,FRUIT_BOX,ROW_NUMBER() OVER (PARTITION BY S_NO ORDER BY FRUITS) RN,
    FRUITS
 FROM T1
 LEFT JOIN T2 ON T2.FRUIT_BOX = T1.BOX
),
cte2 as
(select S_NO,VEGETABLES_BOX,ROW_NUMBER() OVER (PARTITION BY S_NO ORDER BY VEGETABLES) RN,
  VEGETABLES
 FROM T1
 LEFT JOIN T3 ON T3.VEGETABLES_BOX = T1.BOX
),
cte3 as
(SELECT s_no,RN FROM CTE1 union select s_no,rn from cte2)

select cte3.s_no,t1.box,
         cte1.fruits,
         cte2.vegetables 
from cte3
left join cte1 on cte3.s_no = cte1.s_no and cte3.rn = cte1.rn
left join cte2 on cte3.s_no = cte2.s_no and cte3.rn = cte2.rn
left join t1 on t1.s_no = cte3.s_no;

相关问题