SQL JOIN using a mapping table

放肆的年华 提交于 2019-11-30 15:43:42

问题


I have three tables:

COLLECTION 
PERSON 
PERSON_COLLECTION

where PERSON_COLLECTION is a mapping table id|person_id|collection_id

I now want to select all entries in collection and order them by person.name.

Do I have to join the separate tables with the mapping table first and then do a join again on the results?


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/13478715/sql-join-using-a-mapping-table

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