IdkIdk
IdkIdk

Reputation: 3

Mysql Join with 2 foreign keys in same table referencing same key

I have the 2 tables below.

Table: Users

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

Table: 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.

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

Upvotes: 0

Views: 3032

Answers (2)

Gab
Gab

Reputation: 3520

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

Upvotes: 1

Paul Maxwell
Paul Maxwell

Reputation: 35583

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.

Upvotes: 0

Related Questions