1

こんにちは、私はこの SQL 魔女が私に を与えることになっているので、最初が 7 で最後が 10 でmax(messages.message_id) あるレコードを持っていますが、10 を与える代わりに 7 を与えます...完全に を無視してを与えていますまず...これを修正する方法について何か提案はありますか?message_idmessage_idMAX(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

message_idサブクエリ内のテーブルから個別に最新のものを取得できますmessages。その結果は、次の 2 つの条件で一致するテーブルに対して結合され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
于 2013-01-29T06:33:58.920 に答える
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 に答える