[英]How do I make a join on two tables in SQL when there are two foreign keys referencing the same primary key? It's driving me insane
What the title says.标题说什么。 I've tried connecting two tables with two foreign keys referencing the same primary key and cannot get it to work.
我尝试使用两个外键引用相同的主键连接两个表,但无法使其正常工作。
Use table aliases .使用表别名。 For example:
例如:
select *
from money_transfer t
join account s on t.sender_id = s.id
join account r on t.receiver_id = r.id
Here you can see two references to the same PK ( account.id
).在这里,您可以看到对同一个 PK (
account.id
) 的两个引用。 The first time the table is given the alias s
and the second time the same table is given the alias r
.第一次为该表指定别名
s
,第二次为同一表指定别名r
。 This way you can differentiate which one you want to use on each join predicate.这样,您可以区分要在每个连接谓词上使用哪一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.