1

我正在尝试从投票表中获取用户的姓名,但我无法弄清楚如何同时获取选民的姓名和投票者的姓名。

简化投票表

ID   voteeID    voterID
1    1          2
2    1          3
3    1          4
4    2          1
5    2          3
6    2          4

简化的用户信息表

ID   username
1    Bob
2    Sam
3    Ed
4    Mark

我在哪里:

SELECT votes.voteeID, votes.voterID, userinfo.username
FROM votes
JOIN ???

我正在玩加入,但我有点卡住了。如果我将投票者的 id 加入用户信息 id,我将如何获得投票者的姓名,反之亦然?

数据库:MySQL 5

任何帮助甚至提示都会很棒,在此先感谢。

4

4 回答 4

4

试试这个,

SELECT  b.`username` as Votee_Name,
        c.`username` as Voter_Name
FROM    Votes a
            INNER JOIN UserInfo b
                ON a.voteeID = b.Id
            INNER JOIN UserInfo c
                on a.voterID = c.id

SQLFiddle 演示

于 2012-09-05T07:56:28.393 回答
3

像这样的东西怎么样

SELECT  v.ID,
        v.voteeID,
        u1.username Votee,
        v.voterID,
        u2.username Voter
FROM    Votes v INNER JOIN
        User u1     ON  v.voteeID = u1.ID INNER JOIN
        User u2     ON  v.voterID = u2.ID
于 2012-09-05T07:56:54.150 回答
2

您需要花INNER JOIN两次时间才能获得两者的用户名voteevoter

SELECT a.voteeID, a.voterID,
       b.username AS votee_name, c.username AS voter_name
FROM votes a
     INNER JOIN userinfo b
         ON a.voteeID = b.ID
     INNER JOIN userinfo c
         ON a.voterID = c.ID;
于 2012-09-05T07:58:34.800 回答
1

SELECT V.ID as ID B.username as Votee_Name, C.username as Voter_Name FROM Votes V INNER JOIN UserInfo B ON V.voteeID = B.Id INNER JOIN UserInfo C on V.voterID = C.id;

于 2012-09-05T09:55:52.637 回答