✅ SELECT a.unit_price, a.category_id, a.create_time FROM goods a INNER JOIN ( SELECT category_id,max(create_time) AS max_time FROM goods GROUP BY category_id ) AS b ON a.category_id = b.category_id AND a.create_time = b.max_time
执行成功,是我们想要的结果。
INNER JOIN 可以考虑换成LEFT JOIN 加上 IS NULL,作为参照对比性能:
1 2 3 4 5 6 7 8
✅ SELECT a.unit_price, a.category_id, a.create_time FROM goods a LEFT JOIN ( SELECT category_id,max(create_time) AS max_time FROM goods GROUP BY category_id ) AS b ON a.category_id = b.category_id AND a.create_time = b.max_time WHERE b.category_id IS NOT NULL
也可以写在WHERE后的子查询 这里取巧的按ID大小来排序:
1 2 3 4 5 6
✅ SELECT unit_price,category_id,create_time FROM goods WHERE id IN ( SELECT MAX(id) FROM goods GROUP BY category_id )
✅ SELECT * FROM ( SELECT category_id, unit_price, create_time, ROW_NUMBER() OVER ( PARTITIONBY category_id ORDERBY create_time DESC ) as rn FROM goods) t WHERE rn <= 1;
ROW_NUMBER() 就是一个窗口函数
调用窗口函数的格式是:函数名([expr]) OVER子句
其中,PARTITION BY 是分区的意思,我暂时理解为GROUP BY 不做深究
最关键的就是 WHERE 子句后面的内容 :row_number <= 1 感觉是不是回到了ORACLE?