拥有用户表,用户可以拥有多个帐户。 表格如下所示:
u_id | u_parent_d | date_added
1 | 1 | 2017-01-01
2 | 2 | 2017-01-04
3 | 1 | 2017-01-05
4 | 4 | 2017-01-06
5 | 2 | 2017-01-07
如何按添加日期订购这些记录,但将连接的帐户分组在一起
u_id | u_parent_d | date_added
5 | 2 | 2017-01-07
2 | 2 | 2017-01-04
4 | 4 | 2017-01-06
3 | 1 | 2017-01-05
1 | 1 | 2017-01-01
答案 0 :(得分:3)
您可以分两步构建查询。首先获取每个u_parent_d
select u_parent_d, max(date_added) as max_date
from Users
group by u_parent_d
然后,您可以将其与初始表连接,并使用max_date
进行排序
select t1.*
from Users t1
join (
select u_parent_d, max(date_added) as max_date
from Users
group by u_parent_d
) t2
on t1.u_parent_d = t2.u_parent_d
order by t2.max_date desc, t1.date_added desc
答案 1 :(得分:-1)
按日期和父ID排序:
SELECT * FROM users
ORDER BY u_parent_id, date_added DESC