Mysql 在SQL中连接来自同一表的两个外键
不太清楚如何问这个问题,所以如果有人想编辑以更好地表达,请。但是,我想在用户表上联接,但是该行有来自用户表的两个FKMysql 在SQL中连接来自同一表的两个外键,mysql,sql,mariadb,Mysql,Sql,Mariadb,不太清楚如何问这个问题,所以如果有人想编辑以更好地表达,请。但是,我想在用户表上联接,但是该行有来自用户表的两个FK item_tbl id | ownerId | lastModifiedById | itemName ------------------------------------------ 1 | 1 | 2 | "Blog Post" user_tbl id | username ------------- 1 | Joh
item_tbl
id | ownerId | lastModifiedById | itemName
------------------------------------------
1 | 1 | 2 | "Blog Post"
user_tbl
id | username
-------------
1 | John
2 | Sally
期望输出(或类似输出)
目前,我正在进行两次查询以获取此信息。有没有更好(更有效)的方法
为那些好奇的人工作,就像Drew in comments所暗示的那样Schema
FK故障的快速测试:
insert item_tbl(ownerId,lastModifiedById,itemName) values (9,9,'blah');
错误代码:1452。无法添加或更新子行:外键
约束失效
如预期的那样失败,这是一件好事,因为数据不好
成功:
insert item_tbl(ownerId,lastModifiedById,itemName) values (1,2,'the Blog Post is this');
查询 始终加载外键约束以强制引用完整性。一个设计良好的模式的标志是没有任何机会和垃圾被放入 手册第页,共页
缺少的只是考虑将键(索引)添加到
ownerId
和lastModifiedById
列的item_tbl中,以使联接速度更快并避免表扫描FK当然很好,但在选择的stmt中,它们是非常不相关的。如果我没看错的话。我想你要问的是,这是我的数据,我如何获得所需的输出你是对的,这是我试图说ownerId和lastModifiedById与user_tbl.idfair足够相关。而库多正是因为这样做。您需要的是使用两个别名双重连接到用户\u tbl。我打赌你能做到。首先尝试获取所有者的名称。然后,对同一个表进行另一次联接(使用不同的别名),以获取列2Duhhhhhhhhhhhh,谢谢。漫长的工作日哈哈,干得好,jbh,不是很辛苦吗?我想你最后还是弄错了。。。使用人为数据时,复制失败。非常感谢你的帮助。
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
insert item_tbl(ownerId,lastModifiedById,itemName) values (9,9,'blah');
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 |
+----------+----------+-----------------------+