我正在写聊天,请致电"线程"两位用户的讨论 我需要订购这个:
from_id | to_id | message_text | send_time
----------------+---------+--------------+--------------------
24 | 25 |some text | 2016-02-27 18:48:26
36 | 34 |some text | 2016-03-02 16:40:03
24 | 1 |some text | 2016-03-10 17:02:56
83 | 84 |some text | 2016-03-16 11:58:27
84 | 83 |some text | 2016-02-27 18:48:26
83 | 84 |some text | 2016-03-16 12:02:57
25 | 24 |some text | 2016-02-27 18:48:26
84 | 83 |some text | 2016-03-16 12:03:30
就像
from_id | to_id | message_text | send_time
----------------+---------+--------------+--------------------
24 | 25 |some text | 2016-02-27 18:48:26
25 | 24 |some text | 2016-02-27 18:48:26
24 | 1 |some text | 2016-03-10 17:02:56
83 | 84 |some text | 2016-03-16 11:58:27
84 | 83 |some text | 2016-02-27 18:48:26
83 | 84 |some text | 2016-03-16 12:02:57
84 | 83 |some text | 2016-03-16 12:03:30
36 | 34 |some text | 2016-03-02 16:40:03
行必须按时间排序聚合线程和每个线程
答案 0 :(得分:2)
当相同的两个用户进行通信时,无论日期和时间以及之间有多长时间,您都将其称为线程。因此,您只需寻找相同的合作伙伴即可找到线程。线程的密钥可以是least(from_id, to_id), greatest(from_id, to_id)
。将他们的第一次通信时间用作排序键。然后再次加入您的表格以便按顺序获取您的记录。
select m.*
from
(
select
least(from_id, to_id) as lesser_id,
greatest(from_id, to_id) as greater_id,
min(send_time) as sortkey
from mytable
group by least(from_id, to_id), greatest(from_id, to_id)
) thread
join mytable m on least(m.from_id, m.to_id) = thread.lesser_id
and greatest(m.from_id, m.to_id) = thread.greater_id
order by thread.sort_key, thread.lesser_id, thread.greater_id, m.send_time;
答案 1 :(得分:1)
看起来您只想通过from和to id对配对这些值:
select t.*
from t
order by least(from_id, to_id), greatest(from_id, to_id), send_time;