2つのテーブルとユーザー情報を含む別のテーブルを備えたメッセージングシステムに取り組んでいます。
会話は2人以上のユーザー間で行うことができます。すべての会話にはUIDがあり、ユーザー間で交換されるすべてのメッセージにはその会話UIDのラベルが付けられます。
ここに表があります:
conversation_list
:このテーブルのすべての行はとをリンクしuser_id
、conversation_id
ユーザーが最後に会話を表示した時刻も含まれます。
`id` -> unique ID, autoincremented
`user_id` -> This contains the user associated with the conversation.
`conversation_id` -> This contains the UID of the conversation
`date_lastView` -> This field has the time that the user viewed the conversation last
conversation_messages
:このテーブルのすべての行にメッセージが含まれています
`id` -> unique ID, autoincremented
`user_id` -> This contains the user that sent the message.
`conversation_id` -> This contains the UID of the conversation
`date_created` -> This contains the time when the message was posted
`message` -> This contains the message
users
:このテーブルのすべての行にはユーザーが含まれています
`User_ID` -> UID of the user
`FirstName` -> This contains the first name of the user
`LastName` -> This contains the last name of the user
すべての会話の最後のメッセージを取得するためのSQLクエリがすでにあります。ここにあります :
SELECT *
FROM conversation_messages AS m
JOIN
(SELECT mx.conversation_id,
MAX(mx.date_created) AS MaxTime
FROM conversation_messages AS mx
GROUP BY mx.conversation_id) AS mx ON m.conversation_id = mx.conversation_id
AND m.date_created = mx.MaxTime
JOIN
(SELECT mu.conversation_id
FROM conversation_list AS mu
WHERE mu.user_id = :USER_ID_CONNECTED
GROUP BY mu.conversation_id) AS mux ON m.conversation_id = mux.conversation_id
JOIN conversation_list AS mu ON m.conversation_id = mu.conversation_id
GROUP BY mu.conversation_id
ORDER BY m.date_created DESC
ここで、この完全に機能するクエリに、以下を返す機能を追加したいと思います。
- 各会話の未読メッセージの数(ログインしているユーザーよりも
date_creaded
大きいすべてのメッセージの数)date_lastView
User_ID
各会話のすべてのユーザーのを含み、会話で最後にメッセージを投稿した日時でソートされた配列。- 最後の配列については同じ考えですが、ユーザーの
FirstName
とについてです。LastName
いくつか試してみましたが、本当に失敗したので、SOコミュニティに貴重な助けを求めています。
これはすべて、ログインしたユーザーが参加している会話のみを表示できます。
それは役に立ちます、私はSQLFiddleを作成しました