1

你好,我有这个 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
4

2 回答 2

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'

祝你好运。

于 2013-01-29T06:32:45.180 回答
1

您可以单独从子查询中的message_id表中获取最新信息messages,然后如果它在两个条件下匹配,则它的结果将与表相结合:conversation_hashmessage_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
于 2013-01-29T06:33:58.920 回答