MySQL 分组取第一行通常是指在一个查询中对数据进行分组,并从每个分组中选择第一条记录。这在处理聚合数据时非常有用,例如,当你需要获取每个类别的最新记录或最顶端的记录时。
ROW_NUMBER()
, RANK()
, DENSE_RANK()
等。GROUP BY
和 ORDER BY
。假设我们有一个 products
表,结构如下:
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
category_id INT,
name VARCHAR(255),
created_at TIMESTAMP
);
使用窗口函数
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY created_at DESC) as rn
FROM products
) t
WHERE t.rn = 1;
使用子查询
SELECT p1.*
FROM products p1
JOIN (
SELECT category_id, MIN(created_at) as min_created_at
FROM products
GROUP BY category_id
) p2 ON p1.category_id = p2.category_id AND p1.created_at = p2.min_created_at;
使用变量
SET @row_number = 0;
SET @category_id = NULL;
SELECT *
FROM (
SELECT *,
@row_number := IF(@category_id = category_id, @row_number + 1, 1) as row_number,
@category_id := category_id
FROM products
ORDER BY category_id, created_at DESC
) t
WHERE t.row_number = 1;
通过上述方法,你可以根据不同的需求选择合适的方式来获取每个分组的第一行记录。
领取专属 10元无门槛券
手把手带您无忧上云