简体   繁体   English

两个外键引用另一个表的主键

[英]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. personID 和relationID 都是主键。 child_personID and parent_personID are both foreign keys. child_personID 和 parent_personID 都是外键。

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 child.first_name child.last_name 和 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建具有两个主键的表,其中一个是一个表中的外键,另一个是另一个表中的外键? - how to create a table with two primary keys where one is foreign key in one table and the other on another table? SQL 两个外键链接到另一个表的一个主键以从该表中提取字段 - SQL Two foreign keys linked to one primary key of another table to pull field from that table 不同表的两个主键作为另一个表的外键 - Two Primary keys of different tables as foreign keys to another table 将一个表中的外键数组与另一表中的主键匹配? - Match an array of foreign keys in one table with primary key in another table? 选择引用同一个主键表的两个外键的名称 - Select name of two foreign keys referring to same primary key table 无法为设置了两个主键的表创建外键 - Cant create a foreign key for a table that has two primary keys set 更新表以使用两个外键生成主键 - Update table to make primary key out of two foreign keys 有没有办法制作两个主键,只有一个外键引用另一个表的主键 - Is there a way to make two primary keys, with only one foreign key that references another tables primary key 两个主键引用一个外键 - Two primary key reference to a foreign key 两个不同的主键使用相同的外键 - same foreign key for two different primary keys
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM