SQL JOIN using a mapping table

纵饮孤独 提交于 2019-11-30 22:39:58
SELECT
    c.*,
    p.Name
FROM
    Collection c
    JOIN Person_Collection pc ON pc.collection_id = c.id
    JOIN Person p ON p.id = pc.person_id
ORDER BY p.Name

The order you join won't break it but depending on which sql product you're using may effect performance. You need to decide if you want ALL records from both/either table or only records which have a matching mapping entry, this will change the type of join you need to use.

Not sure without the table schema but, my take is:

SELECT
c.*,
p.*

FROM
Person_Collection pc
LEFT JOIN Collection c
ON pc.collection_id = c.id
LEFT JOIN Person p
ON pc.person_id = p.id

ORDER BY p.name
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!