MySQL 按 DESC 和 ASC 使用 order 和 Group By

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3572966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:58:21  来源:igfitidea点击:

Use order by DESC and ASC with Group By

mysql

提问by Hassan

Here is my sql statement

这是我的 sql 语句

 SELECT DISTINCT article_categories.category_id, 
   article_id,article_title,article_intro,article_content,
   category_name_ar 
 FROM articles,article_categories 
 WHERE articles.category_id=article_categories.category_id 
   AND article_type='admin' 
   AND category_case='active' 
 GROUP BY article_categories.category_id 
 ORDER BY article_categories.category_id ASC,
          article_date,article_time DESC 
 LIMIT 10

I would like to retrieve the first DISTINCT 10 categories. In addition I would like to retrieve the equivalent articles where the articles.category_id equals article_categories.category_id. So far the result is good but what I am looking for is to order the result by category_id and in the same time order the result by the article_date,article_time DESC.

我想检索第一个 DISTINCT 10 个类别。此外,我想检索articles.category_id 等于article_categories.category_id 的等效文章。到目前为止,结果很好,但我正在寻找的是按 category_id 对结果进行排序,并在同一时间按 article_date,article_time DESC 对结果进行排序。

Any assistance will be appreciated in advance

任何帮助将提前表示赞赏

回答by spbfox

SELECT distinct c.category_id,...  
FROM articles a,article_categories c
WHERE a.category_id=c.category_id   
AND ...  
AND a.article_id in   
(SELECT max(a1.article_id)   
 FROM articles a1
?WHERE a1.category_id=c.category_id )
ORDER BY c.category_id ASC 

Please replace ... with additional fields and conditions you need.

请将 ... 替换为您需要的其他字段和条件。

回答by Hassan

I got it

我知道了

SELECT DISTINCT article_categories.category_id, 
   article_id,article_title,article_intro,article_content,
   category_name_ar 
 FROM articles,article_categories 
 WHERE articles.category_id=article_categories.category_id 
   AND article_type='admin' 
   AND category_case='active' 
 ORDER BY article_categories.category_id ASC,
          article_date desc,article_time DESC 
 LIMIT 10

Thanks all of your advises, it helped alot

感谢您的所有建议,它帮助了很多

回答by Haim Evgi

only add desclike

只添加desc就像

ORDER BY article_categories.category_id ASC,
          article_date DESC,article_time DESC