Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

joining the same table twice on different columns

Tags:

join

mysql

I've got a user table and a complaint table.

The complaint table has the following structure:

[opened_by]   [complaint_text]   [closed_by]
 (user_id)         (text)         (user_id)
 (user_id)         (text)         (user_id)
 (user_id)         (text)         (user_id)

All users, both the complainers and complaint-resolvers are located in table user.

How do I write a query to show the username for both columns?

This gives me one:

SELECT user.username, complaint.complaint_text
FROM complaint
LEFT JOIN user ON user.user_id=complaint.opened_by

but I don't know how to write it so both _by columns show usernames rather than IDs.

like image 271
Drew Avatar asked Jul 08 '10 07:07

Drew


People also ask

Can you join same table twice?

In a given explore, each join name must be unique. To self join the same table multiple times you can use the from parameter, as mentioned in the docs, to change the "join" name of the table. In this example, we join in person to order twice, with different names and different joining dimensions.

Can you join a table on multiple columns?

You can join tables with multiple columns. That is, you can create a query that matches rows from the two tables only if they satisfy multiple conditions.

How do I join two different columns in the same table in SQL?

SELECT table1.id,table2.id,table2. table3_id_1,table2. table3_id_2,t3_1.id,t3_2.id FROM table1 JOIN table2 ON table1.id=table2.

How can I join two tables twice in SQL?

To form a self-join, you specify the same table twice with different table aliases and provide the join predicate after the ON keyword. In this syntax, the table_name is joined to itself using the INNER JOIN clause.


2 Answers

SELECT 
     complaint.complaint_text, 
     A.username, 
     B.username
FROM 
     complaint 
     LEFT JOIN user A ON A.user_id=complaint.opened_by 
     LEFT JOIN user B ON B.user_id=complaint.closed_by
like image 134
potatopeelings Avatar answered Oct 15 '22 18:10

potatopeelings


I prefer sub-queries as I find them easier to understand...

SELECT (SELECT name
            FROM user
            WHERE user_id = opened_by) AS opener,
       (SELECT name
            FROM user
            WHERE user_id = closed_by) AS closer,
       complaint_text
    FROM complaint;

Sub-queries are usually rewritten by the query optimiser, if you have any performance concerns.

like image 35
Brian Hooper Avatar answered Oct 15 '22 19:10

Brian Hooper