[英]Mysql query to Join two tables
I am writing a simple chat service.我正在编写一个简单的聊天服务。 I want to pick out a messages thread between two people only a sender and a recipient using either their usernames or user ids.
我想选择两个人之间的消息线程,只有发件人和收件人使用他们的用户名或用户 ID。 I have my query below.
我在下面有我的查询。 It has a slight problem, is returning a message twice.
它有一个小问题,正在返回一条消息两次。 How can I fix this?
我怎样才能解决这个问题?
For example if my sender has the uid '101' and my recipient has the username 'janed', my query is例如,如果我的发件人有 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
Users table用户表
---------------------------------
uid |fname |mname |username |
---------------------------------
101 |John |Doe |jdoe |
---------------------------------
102 |Jane |Doe |janed |
---------------------------------
103 |Ann |Other |aother |
---------------------------------
Chat table聊天桌
---------------------------------------------
msg_id |sender |receiver |content |
---------------------------------------------
1 |101 |102 | Hello Jane |
---------------------------------------------
2 |102 |101 | Hello John |
---------------------------------------------
3 |103 |101 | Hi John |
---------------------------------------------
Add a GROUP BY
clause添加
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.