mysql - 有条件的 MySQL 按两个(同等重要的)列排序

标签 mysql sorting conditional-statements

我有一个包含很多列的产品列表,但对我的问题最重要的 3 个是这些(带有一些随机数据):

|--------------------------------------|
| title     | category_id | date       |
| ----------|-------------|------------|
|  Product1 |           1 | 2012-04-18 |
|  Product2 |           1 | 0000-00-00 |
|  Product3 |          17 | 0000-00-00 |
|  Product4 |          17 | 2012-04-10 |
|  Product5 |          17 | 2012-04-20 |
|  Product6 |           1 | 0000-00-00 |
|  Product7 |           2 | 2012-04-20 |
|  Product8 |           2 | 0000-00-00 |
|  Product9 |          17 | 2012-04-16 |
| Product10 |          22 | 2011-11-26 |
| Product11 |          22 | 2011-12-25 |
| Product12 |          30 | 2012-04-01 |
| Product13 |           2 | 2011-12-31 |
| Product14 |          30 | 2010-05-06 |
|--------------------------------------|

具有相同category_id的产品应该一个接一个地列出(此时甚至可以通过“ORDER BY category_id”来解决),但我必须注意 date 列:category_id 和类别中的产品必须按 date 降序排序(category_id 与最新产品在上面等等),所以理想情况下结果集应该是这样的(在类别“组”之间添加换行符只是为了更加透明):

|--------------------------------------|
| title     | category_id | date       |
| ----------|-------------|------------|
|  Product5 |          17 | 2012-04-20 |
|  Product9 |          17 | 2012-04-16 |
|  Product4 |          17 | 2012-04-10 |
|  Product3 |          17 | 0000-00-00 |

|  Product7 |           2 | 2012-04-20 |
| Product13 |           2 | 2011-12-31 |
|  Product8 |           2 | 0000-00-00 |

|  Product1 |           1 | 2012-04-18 |
|  Product2 |           1 | 0000-00-00 |
|  Product6 |           1 | 0000-00-00 |

| Product12 |          30 | 2012-04-01 |
| Product14 |          30 | 2010-05-06 |

| Product11 |          22 | 2011-12-25 |
| Product10 |          22 | 2011-11-26 |
|--------------------------------------|

是否可以仅通过一个查询获得此结果集?什么是可行的解决方案?

提前致谢, 马赛尔

最佳答案

您需要在子查询中找到每个类别的最新日期,将此子查询加入您的表并按 3 个字段排序:

SELECT p.* FROM products p
JOIN
( SELECT category_id, MAX(date) as category_date FROM products
  GROUP BY category_id ) pg
ON p.category_id = pg.category_id
ORDER BY pg.category_date DESC, p.category_id, p.date DESC

关于mysql - 有条件的 MySQL 按两个(同等重要的)列排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10311179/

相关文章:

mysql - 检索每组中的最后一条记录 - MySQL

mysql - 过滤表然后连接结果

javascript - jquery 写一个 if

MySQL 使用内连接进行更新

c++ - 使用 STL 排序功能对列表进行排序

sorting - 无法在一片结构中搜索项目

Java 代码审查 : Merge sorted lists into a single sorted list

javascript - 动态创建 if 条件

比较两个值时 JavaScript 输出和控制流错误

php - 更改 PHP 版本后调用 Xampp 中未定义的函数 mb_detect_encoding() (PHPmyadmin)