简体   繁体   中英

Two foreign keys reference the primary key of another table

So I have two tables

Person(personID, first_name, last_name);
Relation(relationID, child_personID, parent_personID);

personID and relationID are both primary keys. child_personID and parent_personID are both foreign keys.

I want to make a query so I have the first names and last names of both the child and parent.

child.first_name child.last_name and parent.first_name, parent.last_name

One way to go about this is using joins and table aliases . Something like this:

select
    child.first_name,
    child.last_name,
    parent.first_name,
    parent.last_name
from relation r
    join person child on r.child_personID = child.id
    join person parent on r.parent_personID = parent.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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