Search code examples
mysqlsqldatabasemany-to-manyrelational-database

Get information from 2 parent tables referenced in 1 child table


Imagine these tables

Persons

id name
1  John
2  Jane
3  Joe
4  Jill

Things

id name
1  Apple
2  Banana
3  Carrot

Has

pid tid
1    1
1    2
2    3

Where Has is the many-to-many relationship between Persons and Things. How would I be able to get the original parent table information for all Persons and Things that have a relationship?

Basically something like:

pname tname
John  Apple
John  Banana
Jane  Carrot

This sounds like one of the most fundamental SQL things so I know this is a basic question, but I haven't been able to word it properly so I haven't been able to find answers while searching.

The following is the query I tried. I know this would just be the first step, since it gets the Persons involved, but not sure how to get Things as well

SELECT 
    *
FROM
    person p 
    INNER JOIN has h 
    ON p.id = h.pid;

Solution

  • So you continue:

    SELECT . . .   -- the columns you want
    FROM person p INNER JOIN
         has h 
         ON p.id = h.pid INNER JOIN
         thing t
         ON t.id = h.tid;