0

ユーザーからユーザーへのすべてのメッセージを含むMySQLテーブルがあります。

id | to_id /*user_id*/ | from_id /*user_id*/
 1 |  32               |  54
 2 |  54               |  32
 3 |  32               |  54

目標は、ダイアログのリストuser_id-user_idのようなMySQLの回答を日付順に取得することです。しかし、SQLクエリを実行する場合:

select * from messages group by to_id, from_id

私は取得します

 to_id /*user_id*/ | from_id /*user_id*/
  32               |  54
  54               |  32

ただし、最初と2番目の文字列は同じダイアログです。このレコードをグループ化するにはどうすればよいですか?

4

4 に答える 4

2
SELECT DISTINCT LEAST(from_id, to_id), GREATEST(from_id, to_id) FROM messages
于 2012-10-19T09:59:38.483 に答える
1

メッセージテーブルに次のようなフィールドが含まれていると仮定して、次のようmessage_dateにします。

select to_id, from_id, max(message_date) latest_date
from (select to_id, from_id, message_date
      from messages where to_id >= from_id
      union all
      select from_id to_id, to_id from_id, message_date
      from messages where to_id < from_id) m
group by to_id, from_id
order by 3 desc, 1, 2
于 2012-10-19T09:59:19.683 に答える
0

origin_idユーザーが返信した元のメッセージを保存する必要があると思います

次に、レコードをグループ化する方法がありますorigin_id

出発地と目的地のIDだけで他の方法は見当たりません

于 2012-10-19T09:43:27.567 に答える
0
select small_id, big_id, count(*) from
(select id, 
    case when to_id < from_id then to_id else from_id end as small_id, 
    case when to_id < from_id then from_id else to_id end as big_id
from messages) as a 
group by small_id, big_id 
于 2012-10-19T09:56:46.783 に答える