你好我有这个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
答案 0 :(得分:1)
尝试这样的事情:
SELECT
profile.first_name,
profile.last_name,
conversations.conversation_hash,
conversations.person_a,
conversations.person_b,
messages.conversation_hash,
messages.message_id,
messages.message,
messages.subject,
messages.date
FROM conversations
INNER JOIN (SELECT MAX(message_id) as maxMessageId, conversation_hash
FROM messages
GROUP BY conversation_hash) m
ON conversations.conversation_hash=m.conversation_hash
INNER JOIN messages
ON conversations.conversation_hash=messages.conversation_hash AND message.message_id = m.maxMessageId
INNER JOIN profile
ON profile.id=conversations.person_b
WHERE conversations.person_a='$id'
祝你好运。
答案 1 :(得分:1)
您可以在子查询中单独从表message_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