子查詢排序不保留?教你一招解決!
問題詳情:
在 mysql 5.7.13 中,一個用戶有一個產品,只顯示最新的記錄,但子查詢排序后,排序結果不保留。嘗試了分組后再排序,但仍然無法滿足需求。尋求更靠譜、更簡單的寫法。
解決方案:
由于 mysql 5.7 版本不支持窗口函數,因此無法使用窗口函數來實現。不過,這里提供一種思路:
1. 計算每個分組的最大創建時間
select max(create_time) as create_time, user_id, product_id from demo group by user_id, product_id
2. 關聯原表找到對應記錄
將上一步得到的最大創建時間與原表關聯,找到每個分組中最新的記錄。
select t2.id, t1.* from ( select max(create_time) as create_time, user_id, product_id from demo group by user_id, product_id ) t1 left join demo t2 on t1.user_id = t2.user_id and t1.product_id = t2.product_id and t1.create_time = t2.create_time
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END