MYSQL 如何获取分组前的第一行

MYSQL How to fetch the first row before group by

我正在尝试获取按组代码分组的产品,但按售价排序。

当我运行这个查询时:

SELECT p.id, p.base_model, p.group_code, p.retail_price, p.selling_price, option_name
FROM product p
LEFT JOIN product_category pc ON pc.product_id = p.id
LEFT JOIN product_filter_value pfv1 ON p.id = pfv1.product_id
WHERE (pc.category_id = ?
  AND (p.active = ?)
  AND (pfv1.filter_id = ?)
  AND (pfv1.filter_value_id IN (?))
  AND (p.type = "shop")
  AND (p.group_code = ?)
ORDER BY IF(p.combideal_active = 1, p.combideal_price, p.selling_price) asc

我得到这个结果:

当我添加分组时 运行 这个查询:

SELECT p.id, p.base_model, p.group_code, p.retail_price, p.selling_price, option_name
FROM product p
    LEFT JOIN product_category pc ON pc.product_id = p.id
    LEFT JOIN product_filter_value pfv1 ON p.id = pfv1.product_id
WHERE (pc.category_id = ?)
  AND (p.active = ?)
  AND (pfv1.filter_id = ?)
  AND (pfv1.filter_value_id IN (?))
  AND (p.type = "shop")
  AND (p.group_code = ?)
GROUP BY p.group_code
ORDER BY IF(p.combideal_active = 1, p.combideal_price, p.selling_price) asc

我得到这个结果:

您可以看到,这不是第一次查询中最便宜的产品。结果谁能帮我弄到最便宜的?

这种操作很容易在MySQL8.x中执行,使用window函数。但是在MySQL 5.7.

中没有这个东西

但是您可以这样使用 group_concat

select p.*
from   product p
inner join (
    select   p.group_code,
             cast(substring_index(group_concat(p.id 
                 order by if(p.combideal_active = 1, p.combideal_price, p.selling_price) 
                 separator ','
             ), ',', 1) as unsigned) id
    from     product p
    left join product_category pc ON pc.product_id = p.id
    left join product_filter_value pfv1 ON p.id = pfv1.product_id
    where /* ...etc... */
    group by p.group_code
) grouped on  p.id = grouped.id;