简体   繁体   English

2个外键在MySQL中引用相同的主键

[英]2 Foreign Keys referencing the same Primary Key in MySQL

like so: 像这样:

Table-student: 表 - 学生:

sID | sID | name 名称

1 -----susan 1 -----苏珊

2 -----morgan 2 -----摩根

3 -----Ian 3 -----伊恩

4 -----james 4 -----詹姆斯

Primary key = sID 主键= sID

the other table like so: 另一张表是这样的:

Table- friends 表 - 朋友

friendsID | friendsID | personA | personA | personB personB

1-----------1-----------3 1 ----------- ----------- 1 3

2------------1-----------2 2 ------------ ----------- 1 2

3-------------2-----------3 3 ------------- ----------- 2 3

4-------------3------------4 4 ------------- ------------ 3 4

Where Primary Key is: friendsID, personA, personB 主键是:friendsID,personA,personB

Foreign Key = personA, personB which both refer to sID in students table 外键 = personA,personB,它们都引用学生表中的sID

I want a way of querying the friends table in such a way that the personA and personB coloumn are replaced by name via sID. 我想要一种查询朋友表的方式,使得personA和personB coloumn被名称通过sID替换。 I tried natural join but it only works if there is one foreign key. 我尝试过自然连接,但只有在有一个外键时它才有效。

ie Im looking for something like this: 即我正在寻找这样的东西:

friendsID | friendsID | personA | personA | personB personB

1-----------Susan-----------Ian 1 ----------- -----------苏珊伊恩

2------------Sushan-----------Morgan 2 ------------ -----------苏珊摩根

3-------------morgan-----------Ian 3 ------------- -----------摩根伊恩

4-------------Ian------------james 4 ------------- ------------伊恩詹姆斯

the Natural join would work if I only had personB as a column and no personB. 如果我只将personB作为列而没有personB,那么自然联接将起作用。 For some reason the natural join is huge when I do: select*from friends NATURAL JOIN student; 出于某种原因,当我这样做时,自然联接是巨大的:从朋友中选择* NATURAL JOIN student;

Please help. 请帮忙。 Thanks 谢谢

You need to use two joins to accomplish this. 您需要使用两个连接来完成此任务。

For example: 例如:

select f.friendsID, 
  s1.name as personA_name, 
  s2.name as personB_name
from friends f
  inner join student s1 on s1.sID = f.personA
  inner join student s2 on s2.sID = f.personB

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

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