MySQL查询返回2个用户之间的对话

时间:2014-06-18 21:22:29

标签: mysql sql join inner-join parent-child

我正在尝试在2个用户之间的对话中生成消息列表。有2个相关表格:

收件箱

  • id_msg
  • date_msg
  • id_user_from
  • id_user_to
  • 消息

用户

  • id_user
  • 名称

在这个例子中,我是用户ID 1(Jon),与用户ID 2(Anna)聊天。

SELECT SQL_CALC_FOUND_ROWS
i.id_msg,
i.id_user_from AS from,
i.id_user_to AS to,
u.name,
i.message,
FROM inbox AS i
INNER JOIN user AS u ON (u.id_user = i.id_user_from OR u.id_user = i.id_user_to)
WHERE (i.id_user_from = 1 AND i.id_user_to = 2) OR (i.id_user_from = 2 AND i.id_user_to = 1)
    ORDER BY date_msg DESC

目前的问题是重复结果。我收到了2个重复的id_msg值,每个值链接到每个用户的名字,例如:

id  | id_from   | id_to | name  | message
1   | 1         | 2     | Jon   | Hi Anna!
1   | 1         | 2     | Anna  | Hi Anna!
2   | 2         | 1     | Jon   | Hello Jon
2   | 2         | 1     | Anna  | Hello Jon

我应该收到这个:

id  | id_from   | id_to | name  | message
1   | 1         | 2     | Jon   | Hi Anna!
2   | 2         | 1     | Anna  | Hello Jon

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:3)

如果您只想显示from用户,则无需在加入条件中匹配to用户;

SELECT SQL_CALC_FOUND_ROWS
    i.id_msg, i.id_user_from from_id, i.id_user_to to_id,
    u_from.name from_name, u_to.name to_name, i.message
FROM inbox AS i
INNER JOIN user AS u_from ON u_from.id_user = i.id_user_from
INNER JOIN user AS u_to   ON u_to.id_user   = i.id_user_to
WHERE (i.id_user_from = 1 AND i.id_user_to = 2) 
   OR (i.id_user_from = 2 AND i.id_user_to = 1)
ORDER BY date_msg DESC

答案 1 :(得分:1)

这是因为您的join正在使用or。你真的有两个名字,所以他们都应该在查询中。所以,我认为这可能会解决您的问题:

SELECT SQL_CALC_FOUND_ROWS i.id_msg, i.id_user_from AS from, i.id_user_to AS to,
       ufrom.name as fromname, uto.name as toname, i.message,
FROM inbox i INNER JOIN
     user ufrom
     ON ufrom.id_user = i.id_user_from 
     user uto
     ON uto.id_user = i.id_user_to
WHERE (i.id_user_from = 1 AND i.id_user_to = 2) OR
      (i.id_user_from = 2 AND i.id_user_to = 1)
ORDER BY date_msg DESC;