![](/img/trans.png)
[英]Getting child-parent rows from same table; sort by different criteria based on row
[英]SQL sort parent rows in table based on child row values
給出下表:
ID | Name | Time | Parent
1 | Orange | 1493596800 | 0
2 | Apple | 1483228800 | 0
3 | Red Apple | 1493596800 | 2
4 | Yellow Apple | 1493769600 | 2
我想按子行的降序對表格進行排序,並對行進行過濾,以使父級必須為零。
例如:
SELECT *
FROM MyTable as mt1
WHERE Parent = 0
Order
BY
( SELECT mt2.Time
FROM MyTable mt2
WHERE mt2.Parent = mt1.ID
Order BY mt2.Time DESC
Limit 1
) DESC
**輸出必須是:**
2 | Apple | 1483228800 | 0
1 | Orange | 1493596800 | 0
SELECT p.ID, p.Name, MAX(c.Time) AS NewestChildTime, p.Parent
FROM MyTable p
LEFT OUTER JOIN MyTable c
ON c.Parent = p.ID
WHERE p.Parent = 0
GROUP BY p.ID, p.Name, p.Parent
ORDER BY NewestChildTime DESC
select a.* from MyTable a
left join
(
select a.name,max(b.time) time,b.parent from MyTable a
join MyTable b on b.parent=a.id
where b.parent>0 group by a.name,b.parent
) b on b.parent=a.id
where a.parent=0
order by b.time desc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.