简体   繁体   English

当有两个外键引用同一个主键时,如何在 SQL 中的两个表上进行连接? 这让我发疯

[英]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.

相关问题 复合主键包含两个引用相同表的外键:SQL Server与MySQL - Composite primary key comprising two foreign keys referencing same table: SQL Server vs. MySQL 内部联接两个表,都具有没有主键的外键? - Inner join two tables, both have foreign keys with no primary key? 当外键不同时,如何在MySQL中将主键连接到两个外键? - How to join a primary key to two foreign keys in MySQL when the foreign keys will be different? 如何使用相同的主键联接两个表? - How to join the two tables with the same primary key? 两个不同的主键使用相同的外键 - same foreign key for two different primary keys 创建具有引用两个外键的复合主键的表 - Creating a table with composite primary key referencing two foreign keys 引用一个主键的两个外键 - 什么关系? - Two foreign keys referencing to one primary key - what relation? 如何在 SQL 的一个表中使用两个相同的外键命名连接表中的两列? - How to name two columns in join tables with two same foreign key at one table in SQL? 如何用外键引用带有两个主键的表在SQL中创建命令文件? - How to create a command file in SQL with foreign keys referencing a table with two primary keys? 尝试从同一张表引用两个主键时如何解决外键约束? - How to fix foreign key constraint when trying to references two primary keys from the same table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM