MYSQL:左边用相同的字段连接相同的表两次

时间:2018-04-24 17:12:10

标签: mysql left-join self-join

我有一个存储管理员和普通客户的用户表:

ID  Name    Role
1   John    Admin
2   Sara    User
3   Pete    User
4   Nick    User

另一个存储请求的表:

ID  Updatedby    Createdby DateCreated  DateUpdated
1   1              2        10/12/2017   21/01/2018
2   1              1        11/12/2017   22/01/2018
3   1              3        12/12/2017   23/01/2018
4   2              2        13/12/2017   24/01/2018

我正在尝试创建一个如下所示的视图:

ID  Updatedby    Createdby DateCreated  DateUpdated
1   John           Sara     10/12/2017   21/01/2018
2   John           John     11/12/2017   22/01/2018
3   John           Pete     12/12/2017   23/01/2018
4   Sara           Sara     13/12/2017   24/01/2018

创建查询时我遇到的问题是,我试图将连接加入到用户表中两次。如何指定Users.Name是用于Updatedby还是Createdby?这就是我的意思:

SELECT
   request.ID,
   users.Name, /*name for Createdby */
   users.Name, /*name for Updatedby */
   requests.DateCreated,
   requests.DateUpdated
FROM
   requests
LEFT JOIN
   users ON requests.Updatedby = users.ID

我无法理解这一点。

1 个答案:

答案 0 :(得分:0)

这是一个例子:

SELECT toD.dom_url AS ToURL, 
    fromD.dom_url AS FromUrl, 
    rvw.*

FROM reviews AS rvw

LEFT JOIN domain AS toD 
    ON toD.Dom_ID = rvw.rev_dom_for

LEFT JOIN domain AS fromD 
    ON fromD.Dom_ID = rvw.rev_dom_from

您可以使用Alias