Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL JOIN using a mapping table

Tags:

sql

inner-join

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?

like image 828
user871784 Avatar asked Nov 20 '12 17:11

user871784


People also ask

How do I join two tables together SQL?

The join is done by the JOIN operator. In the FROM clause, the name of the first table ( product ) is followed by a JOIN keyword then by the name of the second table ( category ). This is then followed by the keyword ON and by the condition for joining the rows from the different tables.

How do I join two columns from different tables in SQL?

Merging tables by columns. Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other).

Can we join two tables using foreign key?

Many common joins are between two tables related by a foreign key. The most common join restricts foreign key values to be equal to primary key values. The KEY JOIN operator joins two tables based on foreign key relationship.


1 Answers

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
like image 101
Michael Fredrickson Avatar answered Oct 13 '22 18:10

Michael Fredrickson