gpt4 book ai didi

sql - 将两个表,多行合并成一行不同的列

转载 作者:行者123 更新时间:2023-12-04 21:50:15 24 4
gpt4 key购买 nike

我有两张 table 。

USER

USER_ID | USER_NAME
--------------------
659 | John
660 | Andrew
661 | Bianca
--------------------
USER_ADDRESS

USER_ID |TYPE | ADDRESS
------------------------------
659 | HOME | New York
659 | WORK | New Jersey
660 | HOME | San Francisco
660 | WORK | Fremont
------------------------------
我想将第二个表中的多条记录连接到第一个表上的一行中。
USER_ID | USER_NAME | HOME_ADDRESS | WORK_ADDRESS 
--------------------------------------------------
659 | John | New York | New Jersey
660 | Andrew | San Francisco | Fremont
如何在选择查询中获得上述输出?

最佳答案

试试这个:

SELECT u.*, uah.address as home_address, uaw.address as work_address
FROM users u
LEFT OUTER JOIN user_address uah
ON u.user_id = uah.user_id
AND uah.type = 'HOME'
LEFT OUTER JOIN user_address uaw
ON u.user_id = uaw.user_id
AND uaw.type = 'WORK'

关于sql - 将两个表,多行合并成一行不同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38618177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com