LEFT JOIN 3列获取用户名

时间:2011-06-10 13:24:26

标签: mysql left-join

我需要加入三个列,这些列来自3个不同的表,

捐款表:

+-----------+---------------------+
| record_id | contributor_user_id |
+-----------+---------------------+
|         1 |                   2 |
+-----------+---------------------+
|         1 |                   5 |
+-----------+---------------------+

会员表:

+--------------+---------+
| username     | user_id |
+--------------+---------+
| Test         |       1 |
+--------------+---------+
| Test2        |       5 |
+--------------+---------+
| Test3        |       6 |
+--------------+---------+

记录表:

+---------+-----------+
| user_id | record_id |
+---------+-----------+
|      28 |         1 |
+---------+-----------+

我需要返回的是usernameuser_id,用于显示记录所有者。此外,显示usernameuser_id,但这可以是多个(超过1+用户)。我试过这个:

SELECT usr.username,
       usr.user_id,
       rec.record_id,
       contrib.record_id,
       contrib.contributor_user_id
FROM 
(
    records rec

    INNER JOIN members usr ON rec.user_id = usr.user_id

    # this returns records as NULL
    LEFT OUTER JOIN contributions contrib ON rec.record_id = contrib.record_id AND contrib.contributor_user_id = usr.user_id

    # this works, but I need the username to be displayed too
    LEFT OUTER JOIN contributions contrib ON rec.record_id = contrib.record_id
)
WHERE rec.record_id = 1

2 个答案:

答案 0 :(得分:3)

尝试将联接嵌套在左连接内部的贡献用户中。

SELECT u.username, u.user_id, r.record_id, u2.username as ContributorName, u2.user_id as ContributorId
    FROM records r
        INNER JOIN members u
            ON r.user_id = u.user_id
        LEFT JOIN contributions c
            INNER JOIN members u2
                ON c.contributor_user_id = u2.user_id
            ON r.record_id = c.record_id
    WHERE r.record_id = 1

答案 1 :(得分:0)

SELECT
      usr.username             AS record_owner
    , usr.user_id              AS record_owner_id
    , rec.record_id  
    , con.contributor_user_id  AS contributor_id
    , contributors.username    AS contributor_name
FROM 
    records rec
        INNER JOIN
    members usr
            ON rec.user_id = usr.user_id
        LEFT OUTER JOIN
    contributions con
           ON rec.record_id = con.record_id 
        INNER JOIN
    members contributors
            ON con.contributor_user_id = contributors.user_id
WHERE
    rec.record_id = 1