简体   繁体   English

Mysql Join与同一表中的两个外键引用相同的键

[英]Mysql Join with 2 foreign keys in same table referencing same key

I have the 2 tables below. 我有下面的2张桌子。

Table: Users 表:用户

user_id     username
--          --
1           name1
2           name2
3           name3

Table: Rel 表:Rel

user1       user2
--          --
1           2
3           2
1           3

My goal is to retrieve it like this : 我的目标是像这样检索它:

user1       user2
--          --
name1       name2
name3       name2
name1       name3

Excuse my bad terminology and English. 不好意思,我的英语不好。 The user1 and user2 are foreign keys from users.user_id and together they make a composite key. user1和user2是来自users.user_id的外键,它们共同构成一个复合键。

I am able to get one column as below 我可以得到一栏如下

SELECT users.username
FROM users
JOIN rel ON rel.user1 = users.user_id

But when I try to get them together as displayed above in the goal I couldn't manage to get it working at all. 但是,当我试图将它们如上所示实现目标时,我根本无法使其正常工作。 If anybody have any suggestions I would be really grateful 如果有人有任何建议,我将不胜感激

So if your schema is: 因此,如果您的架构是:

CREATE TABLE Users (user_id int, username varchar(50));
INSERT INTO Users (user_id, username) VALUES (1, 'name1');
INSERT INTO Users (user_id, username) VALUES (2, 'name2');
INSERT INTO Users (user_id, username) VALUES (3, 'name3');

CREATE TABLE Rel (user1 int, user2 int);
INSERT INTO Rel (user1, user2) VALUES (1, 2);
INSERT INTO Rel (user1, user2) VALUES (3, 2);
INSERT INTO Rel (user1, user2) VALUES (1, 3);

You can use the following query: 您可以使用以下查询:

SELECT u1.username as user1, u2.username as user2
FROM Rel r
JOIN Users u1 ON r.user1 = u1.user_id
JOIN Users u2 ON r.user2 = u2.user_id

-> ->

+---------+---------+
| user1   | user2   |
|---------+---------|
| name1   | name2   |
| name3   | name2   |
| name1   | name3   |
+---------+---------+
3 rows in set
Time: 0.002s

You should really "just try something" before asking. 在询问之前,您应该真正“尝试一下”。 Try this: 尝试这个:

SELECT u1.username user1, u2.username user2
FROM rel
JOIN users u1 ON rel.user1 = u1.user_id
JOIN users u2 ON rel.user2 = u2.user_id

A most important part to note is that you MUST use "table aliases" to differentiate between the first join and the second join to the same table. 需要注意的最重要部分是,您必须使用“表别名”来区分同一表的第一个联接和第二个联接。 "u1" and "u2" are the aliases I chose for this example. “ u1”和“ u2”是我在此示例中选择的别名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM