joining the same table twice on different columns

后端 未结 4 1960

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

The complaint table has the following structure:

[opened_by]   [         


        
相关标签:
4条回答
  • 2020-12-05 11:56

    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.

    0 讨论(0)
  • 2020-12-05 11:58
    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)

    0 讨论(0)
  • 2020-12-05 12:10

    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
    
    0 讨论(0)
  • 2020-12-05 12:13
    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
    
    0 讨论(0)
提交回复
热议问题