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.
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With