如何在mySql中的GROUP BY之前进行ORDER BY

时间:2018-02-15 05:29:12

标签: mysql group-by sql-order-by

我正在尝试按照降序排列表格的PRIMARY_KEY来订购我的表格(其中包含与产品相关的电子邮件)。然后按产品分组。我想要的只是在顶部显示带有新消息的产品..为此我尝试了

SELECT COUNT(e.product_id) as count,sum(case when e.view='0' then 1 else 0 end) as count_new_enquiry,sum(case when e.reply<>'' then 1 else 0 end) as count_replied_enquiry,e.product_id,p.main_image,p.deleted,p.sold,p.product_status,p.price,p.product_type,br.brand_name_en as brand,m.model_title_en as model,p.built_year 
FROM mecars_email_message e

LEFT JOIN mecars_registration r ON e.user_id = r.user_id
LEFT JOIN mecars_product p ON e.product_id=p.product_id
LEFT JOIN mecars_model m ON e.model_id = m.model_id
LEFT JOIN mecars_brand br ON e.brand_id = br.brand_id

where e.user_id='311'

AND e.deleted = '0'
AND p.deleted = '0'
GROUP BY e.product_id
order by e.email_message_id DESC

LIMIT 0,8

但它没有在顶部显示带有最新消息的产品..然后在搜索后我找到了一个解决方案并将FROM email_message_id替换为FROM (SELECT * FROM mecars_email_message order by email_message_id DESC) e。 并从之前的查询中删除了order by e.email_message_id DESC,但我也无效。

1 个答案:

答案 0 :(得分:-1)

分组子句处理查询返回的行值,当Ordered by子句处理查询返回的列值时。

首先,在使用产品组后,按顺序获得答案降序。