Mysql查询加入两个表

时间:2014-09-14 06:31:55

标签: database join mysqli left-join

我正在写一个简单的聊天服务。我想在两个人之间挑选一个消息线程,只有发件人和收件人 使用他们的用户名或用户ID。我在下面有我的询问。它有一个小问题, 正在返回两次消息。我怎样才能解决这个问题?感谢。

例如,如果我的发件人有uid' 101'我的收件人已使用用户名' janed',我的查询是

SELECT * FROM chat LEFT JOIN users ON sender=uid OR receiver=uid  WHERE username='janed' OR (sender='101' AND receiver='janed') OR (sender='janed' AND receiver='101') ORDER BY msg_id ASC

用户表

---------------------------------
uid |fname  |mname  |username   |
---------------------------------
101 |John   |Doe    |jdoe       |
---------------------------------
102 |Jane   |Doe    |janed      |
---------------------------------
103 |Ann    |Other  |aother     |
---------------------------------

聊天表

---------------------------------------------
msg_id  |sender |receiver   |content        |
---------------------------------------------
1       |101    |102        | Hello Jane    |
---------------------------------------------
2       |102    |101        | Hello John    |
---------------------------------------------
3       |103    |101        | Hi John       |
---------------------------------------------

2 个答案:

答案 0 :(得分:0)

添加GROUP BY子句

SELECT 
    *
FROM
    chat
        LEFT JOIN
    users ON sender = uid OR receiver = uid
WHERE
    username = 'janed'
        OR (sender = '101' AND receiver = 'janed')
        OR (sender = 'janed' AND receiver = '101')
GROUP BY msg_id
ORDER BY msg_id ASC

答案 1 :(得分:-1)

SELECT
    u.*, c.*
  FROM Users u
  LEFT JOIN Chat c ON (
    c.sender = u.uid OR c.receiver = u.uid
  )
  WHERE u.uid = 101 OR u.uid = 102 /* and/or other conditions */
  GROUP BY c.msg_id
  ORDER BY c.msg_id ASC