SQL:连接2个表两次,右侧列相同

时间:2015-05-21 21:28:14

标签: mysql sql-server select join

SQL大师。

在我的MySQL数据库中有以下表格:

Users
----------------------------
UserID  | UserNickName | ...
(PK)    |              |     
----------------------------
1       | Lister       | ...
2       | Rimmer       | ...
3       | Kryten       | ...
----------------------------

Events
-----------------------------------------------------------
EventID | EventCreatedByUserID | EventEdittedByUserID | ...
(PK)    | (FK Users.UserID)    | (FK Users.UserID)    |
-----------------------------------------------------------
1       | 1                    | 2                    | ...
2       | 2                    | 3                    | ...
-----------------------------------------------------------

使用以下查询,我可以选择创建事件的事件条目和用户昵称:

SELECT EventID, ..., UserNickName
FROM Events
   JOIN Users
      ON Users.UserID = Events.EventCreatedByUserID

i.e.
Event #1 | Lister
Event #2 | Rimmer

但是查询如何选择事件条目包括。创建和最后编辑事件的用户昵称是什么样的?

i.e.
Event #1 | Lister | Rimmer
Event #2 | Rimmer | Kryten

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

将连接链接在一起。您必须在用户表上创建别名,因为您使用它两次。

SELECT EventID, ..., CreateUser.UserNickName, EditUser.UserNickName 
FROM Events
JOIN Users CreateUser
ON CreateUser.UserID = Events.EventCreatedByUserID
JOIN Users EditUser
ON EditUser.UserID = Events.EventEditedByUserID

答案 1 :(得分:0)

怎么样:

SELECT e.*, u1.UserNickName AS createdBy, u2.UserNickName AS EditedBy
    FROM Events e
    LEFT JOIN Users u1 ON e.EventCreatedByUserID=u1.UserID
    LEFT JOIN Users u2 ON e.EventEdittedByUserID=u2.UserID
    WHERE ... your additional clauses