【发布时间】:2014-07-14 22:27:27
【问题描述】:
我正在使用 mysql 和 php 构建一个消息传递系统。我已经到了要选择用户收到的消息并计算从不同用户收到的未读消息到同一用户的地步。我已经在下面说明了它
table----users
perID | name |
001 | mum |
002 | tok |
003 | sat |
table----messages
msgID |senderID | msgBody | msgTime | deleted_by_sender |
200 | 002 | Hello | 2014-07-13 19:14:22| no |
201 | 002 | Mate | 2014-07-13 19:14:29| no |
202 | 003 | hi mum | 2014-07-13 19:19:12| no |
203 | 003 | How | 2014-07-13 19:19:52| no |
来自父表 users 的 senderID 引用
table----recipients
recID |msgID |recipientID | msgStatus| deleted_by_recipient|
310 | 200 | 001 | unread | no |
311 | 201 | 001 | unread | no |
312 | 202 | 001 | read | no |
313 | 203 | 001 | read | no |
recipientID 引用父表users
我想要
1. Get only the current message received by the recipient with recipientID=001
if it is not deleted by the recipient.
2. count the number of unread messages received from the individual users.
如下所示
senderID | msgID | unread |
002 | 201 | 2 |
003 | 203 | 0 |
我下面的查询按预期工作,但它隐藏了最后一行,因为它在 msgStatus 列中没有未读值,
但我希望即使msgStatus 没有任何价值,也会返回所有行。它也应该在一个优化的查询中。
SELECT *,count(msgStatus) As unread
FROM (
SELECT
m.senderID,
m.msgTime,
u.perID,
r.recipientID,
r.msgID,
r.msgStatus,
r.deleted_by_recipient
FROM
messages m
INNER JOIN
users u
ON
m.senderID=u.perID
INNER JOIN
recipients r
ON
r.msgID=m.msgID
ORDER BY msgTime DESC
)h
WHERE
recipientID=12 and
deleted_by_recipient ='no' and
msgStatus='unread'
GROUP BY perID
感谢您的帮助。
【问题讨论】: