mysql - 对包含零的列进行条件 ORDER BY

标签 mysql sql

我有一个无法解决的问题。假设我有这个表,items 有 6 条记录

item_id     passage_id
==========  ==========
6           0
5           3
4           0
3           0
2           3
1           3

To get the records by descending item_id, I run the statement SELECT * FROM items ORDER BY item_id DESC, and the result is simply the same as the source table above.

But now it gets tricky. I now want to sort by descending item_id, but if there are other items with the same passage_id, I want them grouped by that passage_id.

item_id     passage_id
==========  ==========
6           0
5           3
2           3
1           3
4           0
3           0

How can I do this in a single SQL statement? The order is crucial because I need preserve it even when a limit is used:

SELECT * FROM items ORDER BY ??? LIMIT 0, 3

item_id     passage_id
==========  ==========
6           0
5           3
2           3

SELECT * FROM items ORDER BY ??? LIMIT 2, 3

item_id     passage_id
==========  ==========
1           3
4           0
3           0

EDIT: Here's the answer, taken from Gordon Linoff's answer below

SELECT i.item_id, i.passage_id 
FROM items i LEFT JOIN (
    SELECT i.passage_id, MAX(i.item_id) AS imax_id
    FROM items i 
    GROUP BY i.passage_id
) imax 
ON i.passage_id = imax.passage_id 
ORDER BY CASE WHEN i.passage_id=0 THEN i.item_id  ELSE imax.imax_id END DESC, i.item_id DESC;

最佳答案

如果我理解正确的话,您需要执行一些操作,例如将 passage_id 放在一起并按项目 ID 对这些组进行排序。实际上应该执行以下操作:

select i.item_id, i.passage_id
from items i join
     (select i.passage_id, max(i.item_id) as maxiid
      from items i
      group by i.passage_id
     ) imax
     on i.passage_id = i.passage_id
order by imax.maxiid,
         i.item_id desc;

但是,由于 passage_id = 0,它不会生成您的订单。对于这些,您似乎希望它们仅基于 item_id 本身。所以,我认为这概括了您的逻辑:

select i.item_id, i.passage_id
from items i join
     (select i.passage_id, max(i.item_id) as maxiid
      from items i
      group by i.passage_id
     ) imax
     on i.passage_id = i.passage_id
order by (case when i.passage_id = 0 then i.item_id else imax.maxiid end) desc,
         i.item_id desc;

关于mysql - 对包含零的列进行条件 ORDER BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24001855/

相关文章:

mysql - Laravel获取MySQL在Eloquent模型中查询Builder语句

php - 如何将出生日期转换为年龄并将其保存到表格中?

sql - 您什么时候会在数据库标识字段上设置增量值?

sql - 如何处理返回多个值的子查询

php - 尝试插入时出现 SQL 语法错误

MySQL 过程返回 NULL 而不是现有数据

java - 最新版本的 spring boot 问题

mysql - 将 perl 与 mysql 连接时,用户 'root' @'localhost'(使用密码 yes)的访问被拒绝

mysql - 如何用 1000 行示例数据填充表?

mysql用逗号分隔的id连接两个表