我正在做的是尝试按最后的消息进行排序。
我正在尝试选择存储在'conversations_messages'表中的最后一次作为'message_date'行(整数),但查询返回NULL,而不是最大时间。
这是SQL查询:
SELECT conversations.id, conversations.subject, conversations.sender,
MAX(conversations_messages.message_date) AS 'last_reply',
MAX(conversations_messages.message_date) > conversations_users.last_view AS 'unread'
FROM conversations
LEFT JOIN conversations_messages ON conversations.id=conversations_messages.message_id
INNER JOIN conversations_users ON conversations.id=conversations_users.conversation_id
WHERE conversations_users.user_id=$user_id AND conversations_users.deleted=0
GROUP BY conversations.id
ORDER BY 'last_reply' DESC
除了返回为NULL的'last_reply'之外,查询运行良好 - 这是我的问题。
我尝试通过将查询拆分为两个查询来解决问题,我的新查询是:
SELECT MAX(conversations_messages.message_date) AS 'last_reply',
MAX(conversations_messages.message_date) > conversations_users.last_view AS 'unread'
FROM conversations_messages
LEFT JOIN conversations ON conversations_messages.message_id=conversations.id
INNER JOIN conversations_users ON conversations_messages.conversation_id=conversations_users.conversation_id
WHERE conversations_messages.conversation_id = $id
此查询运行良好并返回正确的值,但我需要以某种方式将其合并到第一个查询中。我试了几个小时但没有成功。
谢谢。