tags:

views:

41

answers:

4

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.

+5  A: 
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
potatopeelings
A: 
SELECT user1.username AS opened_by_username, complaint.complaint_text, user2.username AS closed_by_username
FROM user AS user1, complaint, user as user2
WHERE user1.user_id = complaint.opened_by
AND user2.user_id = complaint.closed_by

Join it again using an alias (thats what the user as user2 stuff is about)

Mailslut
A: 

Use this query:

SELECT opener.username as opened_by, complaint.complaint_text, closer.username as closed_by
FROM complaint
LEFT JOIN user as opener ON opener.user_id=complaint.opened_by
LEFT JOIN user as closer ON closer.user_id=complaint.closed_by
Kangkan
A: 

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.

Brian Hooper