在不同的列上连接两次相同的表

时间:2010-07-08 07:13:40

标签: mysql join

我有一张user表和一张complaint表。

complaint表具有以下结构:

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

所有用户,投诉人投诉解析器都位于表user中。

如何编写查询以显示两列的用户名?

这给了我一个:

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

但我不知道如何编写它,因此_by列都显示用户名而不是ID。

4 个答案:

答案 0 :(得分:34)

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

答案 1 :(得分:1)

我更喜欢子查询,因为我觉得它们更容易理解......

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;

如果您有任何性能问题,则查询优化器通常会重写子查询。

答案 2 :(得分:0)

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

使用别名再次加入它(这就是用户作为user2的内容)

答案 3 :(得分:0)

使用此查询:

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