在 SQL 中连接来自相同 table 的两个外键

join on two foreign keys from same table in SQL

不太确定如何提出这个问题,所以如果有人想编辑以更好地表达,请。但是我想加入一个用户 table 但是该行有两个来自用户 table

的 FK
item_tbl
id | ownerId | lastModifiedById | itemName
------------------------------------------
1  |       1 |                2 | "Blog Post"

user_tbl
id | username
-------------
1  |     John
2  |    Sally

期望的输出(或类似的东西)

Owner Username | last modified by |       item
----------------------------------------------
          John |            Sally | "Blog Post"

目前我正在执行两个查询以获取此信息。有更好的(阅读:更有效的)方法吗?

SELECT user_tbl.username Owner, a.username Modifier, item_tbl.itemName 
FROM item_tbl 
JOIN user_tbl 
ON item_tbl.ownerId = user_tbl.id 
JOIN user_tbl a 
ON item_tbl.lastModifiedById = a.id;

正如德鲁在评论中所暗示的那样,为那些好奇的人工作

架构

create table user_tbl
(   id int auto_increment primary key,
    username varchar(50) not null
);

create table item_tbl
(   id int auto_increment primary key,
    ownerId int not null,
    lastModifiedById int not null,
    itemName varchar(50) not null,
    CONSTRAINT fk_own_user FOREIGN KEY (ownerId) REFERENCES user_tbl(id),
    CONSTRAINT fk_mod_user FOREIGN KEY (lastModifiedById) REFERENCES user_tbl(id)
);
insert user_tbl(username) values('John');   -- this becomes id 1
insert user_tbl(username) values('Sally');  -- this becomes id 2

FK 失败快速测试:

insert item_tbl(ownerId,lastModifiedById,itemName) values (9,9,'blah');

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails

不出所料,这是好事,因为数据不好

成功:

insert item_tbl(ownerId,lastModifiedById,itemName) values (1,2,'the Blog Post is this');

查询

select u1.username,u2.username,i.itemName 
from item_tbl i 
join user_tbl u1 
on u1.id=i.ownerId 
join user_tbl u2 
on u2.id=i.lastModifiedById;
+----------+----------+-----------------------+
| username | username | itemName              |
+----------+----------+-----------------------+
| John     | Sally    | the Blog Post is this |
+----------+----------+-----------------------+

始终加载外键约束以实施参照完整性。一个设计良好的模式的标志是没有机会和垃圾被放入。

Foreign Key Constraints 上的手册页。

所有缺少的是考虑为 ownerIdlastModifiedById 列添加到 item_tbl 的键(索引)以使连接速度更快并避免 table 扫描