mysql中按某个字段分组获取最新的数据的场景还是很多的。如果获取用户最新的获取车系记录等等。
这里依赖了的int类型的主键,作为关联查询的key。
SELECT t1.*
FROM car_browsed_record t1
JOIN (
SELECT car_series_id, MAX(id) AS max_id
FROM car_browsed_record
GROUP BY car_series_id
) t2
ON t1.id = t2.max_id
order by id desc
貌似mysql8才被支持,原理就是先按PARTITION BY分区并指定字段排序后得到一个rownum。那么row_num最小的也就是我们需要获取的这一条数据
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY car_series_id ORDER BY id DESC) AS row_num
FROM car_browsed_record
) t
WHERE t.row_num = 1
order by id desc