mysql内部连接两列上的一个表

时间:2014-07-30 17:00:59

标签: mysql

我使用的Mysql查询如下所示:

SELECT messages.*,users.name,users.pic 
FROM messages 
INNER JOIN users 
ON users.hash = '123456789' 
WHERE (( receive='987654321' AND send='123456789') 
OR (receive='123456789'  AND send='987654321' )) 
ORDER BY id_message desc

此查询返回正确的结果,但我需要除了照片和发送消息的人的姓名(" pic"和#34;名称"表中的字段)也图片和收到邮件的人的姓名。

我需要的结果应该是:

  id_message  |    name  |   pic    |   messages  |   send    |   receive  
 ------------------------------------------------------------------------
      4       |  john    |  1.jpg   |     text 1  | 123456789 |  987654321
      3       |  merry   |  2.jpg   |     text 2  | 987654321 |  123456789
      2       |  merry   |  2.jpg   |     text 3  | 987654321 |  123456789 
      1       |  john    |  1.jpg   |     text 4  | 123456789 |  987654321

我需要在此查询中修改哪些内容才能获得正确的结果? 我感谢任何帮助...

编辑:

"用户"表:

   hash     |  name  |   pic  
 ------------------------------
 123456789  |  john  |   1.jpg
 987654321  |  merry |   2.jpg

"消息"表:

   id_message  |   receive   |   send     | messages
  ---------------------------------------------------
        1      |  987654321  | 123456789  |   text 1 
        2      |  123456789  | 987654321  |   text 2 
        3      |  123456789  | 987654321  |   text 3 
        4      |  987654321  | 123456789  |   text 4 

1 个答案:

答案 0 :(得分:0)

假设您需要收到该邮件的人的照片与发送邮件的人的图片在同一行,那么您需要加入users表两次。另外假设你想要一个不同的列用于这些名称和照片,如下所示:

SELECT messages.*,senders.name,senders.pic, receivers.name as rec_name, receivers.pic as rec_pic 
FROM messages 
INNER JOIN users senders
ON users.hash = '123456789' 
and (( receive='987654321' AND send='123456789') 
inner join users as receivers  
on receivers.hash = messages.receive
ORDER BY id_message desc