如何在Mysql中查询获取用户名和相同查询以从同一用户表中获取另一个用户名?

时间:2012-02-23 19:43:19

标签: mysql sql

我有两张桌子:

Users                          Mail
-------                        ------
ID | Username                  ID | UserID | SenderID   | Something
---------------                ---------------------------------------------------
1  | A                         1  |  2     |  1         | Becoming Mad with SQL
2  | B                         2  |  3     |  4         | Mee too

我正在尝试这个:

SELECT *
 a.userid, a.senderid, a.something,
 b.username
FROM
 mail a
 LEFT JOIN users b on b.id=a.senderid
WHERE
 a.id='1'

输出/类似:

a.Userid | a.senderid | a.something | b.username
--------------------------------------------------
2      | 1            | becoming..  | A

我的预期输出是这样的(用户名B和A在一行中):

Userid | senderid | something | username | Username of UserID
---------------------------------------------------------------
2      | 1        | becoming..| A        | B

如何在同一查询中获取UserID及其用户名?因为我已经有left join users b on b.id=a.senderid

2 个答案:

答案 0 :(得分:2)

SELECT  a.userid, 
        a.senderid, 
        a.something,
        b.username, 
        c.username
FROM    mail a
        LEFT JOIN users b ON b.id = a.senderid
        JOIN      users c ON c.id = a.UserID
WHERE   a.id='1'

答案 1 :(得分:2)

使用两个用户表副本,一个用于发件人,一个用于用户。

   SELECT a.userid, 
           a.senderid, 
           a.something,  
           b.username,
           c.username 
   FROM  mail a,  
         users b,
         users c
   WHERE  a.id='1'
   AND  b.id=a.senderid
   AND  c.id=a.Userid 

确保您在表中也为邮件的id列和用户senderid和用户ID列添加索引 - 它们将有助于加快速度。