繁体   English   中英

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

[英]Joining two tables, multiple rows into a single row different columns

我有两张桌子。

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM