7

2つのテーブルとユーザー情報を含む別のテーブルを備えたメッセージングシステムに取り組んでいます。
会話は2人以上のユーザー間で行うことができます。すべての会話にはUIDがあり、ユーザー間で交換されるすべてのメッセージにはその会話UIDのラベルが付けられます。

ここに表があります:

conversation_list:このテーブルのすべての行はとをリンクしuser_idconversation_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を作成しました

4

2 に答える 2

3

ユーザーの会話 (ここではユーザー #6) の未読メッセージの数:

SELECT l.conversation_id, count(*)
FROM   conversation_list l
JOIN   conversation_messages m ON m.conversation_id = l.conversation_id AND m.date_created > l.date_lastview
WHERE  l.user_id = 6
GROUP BY l.conversation_id

最後のアクティビティで並べ替えられた会話の参加者:

SELECT conversation_id, user_id, max(date_created) as last_active
FROM   conversation_messages
GROUP BY conversation_id, user_id
ORDER BY conversation_id, last_active

3 番目のクエリは、2 番目のクエリと同じように、 でもう 1 つのテーブルを結合するだけuser_idですよね?

于 2012-06-09T18:21:23.047 に答える