你好,我有一个SQL女巫应该给我max(messages.message_id)
所以我有一个记录,第一个message_id
是7,最后一个message_id
是10,但不是给我10,而是给我7。。。它完全忽略了MAX(messages.message_id)
,给了我第一个message_id
。。。关于如何解决这个问题有什么建议吗?
SELECT
profile.first_name,
profile.last_name,
conversations.conversation_hash,
conversations.person_a,
conversations.person_b,
messages.conversation_hash,
MAX(messages.message_id),
messages.message,
messages.subject,
messages.date
FROM conversations
INNER JOIN messages
ON conversations.conversation_hash = messages.conversation_hash
INNER JOIN profile
ON profile.id = conversations.person_b
WHERE conversations.person_a = '$id'
GROUP BY messages.conversation_hash
ORDER BY messages.message_id DESC
桌子:
对话:
conversation_id | conversation_hash | person_a | person_b |
信息:
conversation_hash | from_id | to_id | message_id | subject | message | date
最佳答案
您可以从子查询中的tablemessage_id
单独获取最新的messages
,然后将其结果与表连接起来,前提是它在两个条件下匹配:conversation_hash
和message_id
。
完整查询:
SELECT profile.first_name,
profile.last_name,
conversations.conversation_hash,
conversations.person_a,
conversations.person_b,
messages.*
FROM conversations
INNER JOIN messages
ON conversations.conversation_hash = messages.conversation_hash
INNER JOIN
(
SELECT conversation_hash, MAX(message_id) max_ID
FROM messages
GROUP BY conversation_hash
) c ON messages.conversation_hash = c.conversation_hash AND
messages.message_id = c.max_ID
INNER JOIN profile
ON profile.id=conversations.person_b
WHERE conversations.person_a='$id'
ORDER BY messages.message_id DESC