2 Foreign Keys referencing the same Primary Key in MySQL(2 引用 MySQL 中相同主键的外键)
问题描述
像这样:
表学生:
sID |名字
1 -----苏珊
2 -----摩根
3 -----伊恩
4 -----詹姆斯
主键 = sID
另一张桌子是这样的:
桌友
朋友ID |人A |人B
friendsID | personA | 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
其中主键是:friendsID、personA、personB
Where Primary Key is: friendsID, personA, personB
外键 = personA, personB 都引用学生表中的sID
Foreign Key = personA, personB which both refer to sID in students table
我想要一种查询朋友表的方法,通过 sID 将 personA 和 personB 列替换为名称.我尝试了自然连接,但它只有在有一个外键时才有效.
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. I tried natural join but it only works if there is one foreign key.
即我正在寻找这样的东西:
i.e. Im looking for something like this:
朋友ID |人A |人B
friendsID | personA | personB
1------------苏珊------------伊恩
1-----------Susan-----------Ian
2------------苏珊------------摩根
2------------Sushan-----------Morgan
3-------------摩根------------伊恩
3-------------morgan-----------Ian
4-------------伊恩------------詹姆斯
4-------------Ian------------james
如果我只有 personB 作为列而没有 personB,自然连接将起作用.出于某种原因,当我这样做时,自然连接是巨大的:select*from friends NATURAL JOIN student;
the Natural join would work if I only had personB as a column and no personB. For some reason the natural join is huge when I do: select*from friends NATURAL JOIN student;
请帮忙.谢谢
推荐答案
您需要使用两个连接来完成此操作.
You need to use two joins to accomplish this.
例如:
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
这篇关于2 引用 MySQL 中相同主键的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:2 引用 MySQL 中相同主键的外键
基础教程推荐
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在多列上分布任意行 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- oracle区分大小写的原因? 2021-01-01
