SQL JOIN 获取每行两条记录
SQL JOIN to get two records for each row
我有两个table,说
TABLE: Transactions
COLUMNS: sender_id, receiver_id, value
和
TABLE: Users
COLUMNS: user_id, username
是否可以为交易 table 中的每条记录创建一个 SQL 语句来 JOIN 来自用户 table 的两行?因此,对于每个结果行,我应该有两个来自用户 table 的用户名,但有两个不同的别名。如何实现?
谢谢
关于别名,你的想法是对的。您需要两个连接:
select us.username, ur.username, t.value
from transactions t left join
users us
on t.sender_id = us.user_id left join
users ur
on t.receiver_id = ur.receiver_id;
left join
是为了防止其中一个值不匹配。
假设 sender_id
和 receiver_id
是对 user_id
的引用,并假设 user_id
在 Users
table 中是唯一的。 .. 是的。
加入 Users
table 两次。
例如:
SELECT t.sender_id
, t.receiver_id
, t.value
, s.user_id AS sender_user_id
, s.username AS sender_username
, r.user_id AS receiver_user_id
, r.username AS receiver_username
FROM `Transactions` t
LEFT
JOIN `Users` s ON s.user_id = t.sender_id
LEFT
JOIN `Users` r ON r.user_id = t.receiver_id
ORDER BY 1,2,3
查询正在使用外部联接...如果 receiver_id
或 sender_id
与 Users
中的行不匹配,将返回 Transactions
中的行table.
可以删除关键字 LEFT
以更改该行为,因此仅当 Users
中存在与 sender_id
和 [=12 匹配的行时才会返回一行=].
我有两个table,说
TABLE: Transactions
COLUMNS: sender_id, receiver_id, value
和
TABLE: Users
COLUMNS: user_id, username
是否可以为交易 table 中的每条记录创建一个 SQL 语句来 JOIN 来自用户 table 的两行?因此,对于每个结果行,我应该有两个来自用户 table 的用户名,但有两个不同的别名。如何实现?
谢谢
关于别名,你的想法是对的。您需要两个连接:
select us.username, ur.username, t.value
from transactions t left join
users us
on t.sender_id = us.user_id left join
users ur
on t.receiver_id = ur.receiver_id;
left join
是为了防止其中一个值不匹配。
假设 sender_id
和 receiver_id
是对 user_id
的引用,并假设 user_id
在 Users
table 中是唯一的。 .. 是的。
加入 Users
table 两次。
例如:
SELECT t.sender_id
, t.receiver_id
, t.value
, s.user_id AS sender_user_id
, s.username AS sender_username
, r.user_id AS receiver_user_id
, r.username AS receiver_username
FROM `Transactions` t
LEFT
JOIN `Users` s ON s.user_id = t.sender_id
LEFT
JOIN `Users` r ON r.user_id = t.receiver_id
ORDER BY 1,2,3
查询正在使用外部联接...如果 receiver_id
或 sender_id
与 Users
中的行不匹配,将返回 Transactions
中的行table.
可以删除关键字 LEFT
以更改该行为,因此仅当 Users
中存在与 sender_id
和 [=12 匹配的行时才会返回一行=].