我想在我遇到的查询中提出一些帮助。
基本上,我有三张桌子:
'users',将用户的所有数据存储在db中,字段为:
'files',存储用户的文件,字段为:
'chat',存储用户的所有聊天消息,字段为:
我需要做的是恢复用户最近聊过的所有用户,我这样做:
SELECT U.usr_id,
C.chat_fromname,
F.fil_uid
FROM users AS U chat AS C,
files AS F
WHERE C.chat_from = U.usr_id
AND F.fil_uid = U.usr_profile_photo_id
AND U.usr_id IN
(
SELECT G.chat_from
FROM chat AS G
WHERE G.chat_to = 1
UNION SELECT D.chat_to
FROM chat AS D
WHERE D.chat_from = 1
)
GROUP BY U.usr_id,
C.chat_fromname,
F.fil_uid
ORDER BY C.chat_sent DESC;
问题是查询似乎没有像我期望的那样,导致它返回最近与用户聊天的用户,但是没有按发送的聊天消息的日期排序(chat_sent列),似乎MySQL是无视订单条款,或者我错了什么?
如何检索最近以正确方式订购的用户?
编辑:可能更好的解决方案:
SELECT chat_from, chat_fromname
FROM chat AS C
WHERE C.to = 1
GROUP BY chat_from, chat_fromname
ORDER BY MAX(C.chat_sent) DESC
LIMIT 10;
在这里,我向用户恢复了向用户传达消息的最后10个用户(因此用户是接收者)。
然后像:
SELECT U.usr_id, F.fil_uid
FROM users AS U, files AS F
WHERE F.fil_uid = U.usr_profile_photo_id AND (
-- dinamically built based on the previous result.
U.usr_id = 1 OR
U.usr_id = 2 OR
U.usr_id = 3 OR
U.usr_id = 4 OR
U.usr_id = 5 OR
U.usr_id = 6 OR
U.usr_id = 7 OR
U.usr_id = 8 OR
U.usr_id = 9 OR
U.usr_id = 10);
但这里的问题是我只向用户恢复了WROTE的用户,我希望能够明白......例如,如果用户向用户8写了一些东西(所以用户8是chat_to接收者) ?