join on two foreign keys from same table in SQL(在 SQL 中加入来自同一个表的两个外键)
问题描述
不太清楚如何问这个问题,所以如果有人想编辑以更好地表达,请.但是我想加入一个用户表,但是该行有两个来自用户表的 FK
Not quite sure how to ask this question so if someone wants to edit to better articulate please. However I want to join on a user table however the row has two FKs from the user table
item_tbl
id | ownerId | lastModifiedById | itemName
------------------------------------------
1 | 1 | 2 | "Blog Post"
user_tbl
id | username
-------------
1 | John
2 | Sally
期望的输出(或类似的东西)
Desired output (or something like it)
Owner Username | last modified by | item
----------------------------------------------
John | Sally | "Blog Post"
目前我正在执行两个查询来获取此信息.有没有更好(阅读:更有效)的方法?
currently i'm doing two queries to get this information. Is there a better (read: more efficient) way?
推荐答案
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;
为那些好奇的人工作,正如 Drew 在评论中暗示的那样
worked for those curious as hinted at by Drew in comments
这篇关于在 SQL 中加入来自同一个表的两个外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 SQL 中加入来自同一个表的两个外键
基础教程推荐
- 在 SQL 中连接多个表 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
