MySQL如何在对行进行分组之前对其进行排序?

时间:2018-10-31 15:21:35

标签: php mysql

我尝试针对每种尺寸,品牌和种类仅返回1行,但有时会有多行具有与enddate完全相同的值。

我想返回最高enddate(按enddate desc排序)的行。

SELECT 
    promotion.id,
    promotion.uid,
    promotion.promotion_id,
    promotion.url,
    promotion.shop_id,
    promotion.brand_kind_id,
    promotion.before_price,
    promotion.after_price,
    promotion.brand_id,
    promotion.brand_package_id, 
    promotion.brand_size, 
    promotion.amount, 
    promotion.begindate,
    promotion.enddate

FROM 
    `promotion`     

WHERE 
    AND (promotion.url is not null AND promotion.url != '')

GROUP BY 
    promotion.brand_id,
    promotion.brand_kind_id,
    promotion.brand_size

ORDER BY 
    promotion.enddate DESC

1 个答案:

答案 0 :(得分:0)

如果特定的问题是某些行的结束日期不同,则建议从选择的字符串中删除结束日期。这意味着将不考虑结束日期不同的行。

另一种选择是选择最大结束日期,您可以尝试以下操作:

SELECT 
    promotion.id,
    promotion.uid,
    promotion.promotion_id,
    promotion.url,
    promotion.shop_id,
    promotion.brand_kind_id,
    promotion.before_price,
    promotion.after_price,
    promotion.brand_id,
    promotion.brand_package_id, 
    promotion.brand_size, 
    promotion.amount, 
    promotion.begindate,
    MAX(promotion.enddate)
FROM 
    `promotion`     
WHERE 
    AND (promotion.url is not null AND promotion.url != '')
GROUP BY 
    promotion.brand_id,
    promotion.brand_kind_id,
    promotion.brand_size
ORDER BY 
    promotion.enddate DESC

但是,仅当您打算将结束日期用作数据时,我才建议使用此方法。