我正在构建一个消息传递系统,下面是我的表格。
table --users
|u_id | Name |
| 01 | Aku |
| 02 | Sika |
| 03 | Admin|
table --messages
|m_id | sender_id | Body | sender_deleted | msgTime |
| 100 | 01 | hello | Yes | 16:04 |
| 200 | 02 | Hi | no | 16:08 |
table --recipient
|m_id | recipient_id | status | recipient_deleted |
|100 | 02 | read | no |
|200 | 01 | unread | no |
问题
我想从这些表中查询仅在两方之间的对话(因此u_id=01和u_id=02
),我再次想在sender_deleted=yes<时隐藏发送给sender_id的消息
但如果 recipient_deleted = no
recipient_id
显示相同的消息
NB-更新
我希望
u_id=01
的用户在其页面上查看时只能看到带有m_id=200
的消息我希望
u_id=02
的用户在其页面上查看时能够看到包含m_id=100
和m_id=200
的消息
这是我尝试过的,但我不知道如何去做
SELECT
m.sender_id,
m.Body,
u.Name,
u.u_id
FROM
messages m
LEFT JOIN
users u
ON
m.sender_id=u.u_id
LEFT JOIN
recipient r
ON
r.m_id=m.m_id
WHERE
(m.sender_id=01 OR m.sender_id=02 ) and
(r.recipient_id=01 OR r.recipient_id=02)
最佳答案
这是一种解决方案。它的工作原理是过滤用户 01 和 02 之间交换的消息,并仅显示与登录用户相关的消息:
SELECT m.sender_id, m.recipient_id, m.Body, u_sender.Name as Sender,
u_recipient.Name as Recipient, sender_deleted, recipient_deleted
FROM messages m
JOIN recipient r ON (m.m_id=r.m_id)
JOIN user u_sender ON (m.sender_id=u_sender.u_id)
JOIN user u_recipient ON (r.recipient_id=u_recipient.u_id)
WHERE
m.sender_id IN (01,02)
AND
r.recipient_id ON (01,02)
AND
((m.sender_id=<id> AND m.sender_deleted='no')
OR
(r.recipient_id=<id> AND r.recipient_deleted='no'))
您应该替换<id>
登录的用户 ID(01 或 02)
当然,您可以更改返回的字段以显示您需要的内容。
希望这有帮助!
关于mysql - 查询两方之间的消息,但对删除的用户隐藏消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24600293/