按顺序排序,parent_id 和组?

Order By order, parent_id and group?

我真的不确定如何准确表达我想要做的事情,因此我在搜索时遇到了问题。我有一个 pages 的 table,每个 idtitleorderparent_id 如果 parent_idNULL 这被认为是顶级页面。我几乎可以使用 ORDER BY by parent_idorder 通过以下查询对它进行正确排序:


select `id`, `title`, `order`, `parent_id`
from pages
order by `order` AND COALESCE(`parent_id`, `order`), `parent_id` is not null, `order`

查询吐出以下内容:

id title order parent_id
107fa138 video 0 NULL
8eeda86c mn 2 NULL
cac640ad xxe title 3 NULL
1ce4d070 sdfsdfsdf 4 NULL
b45dc24d another 1 8eeda86c
d3490141 hello 9 8eeda86c

这就是几乎我想要的。理想情况下,我将带有 parent_id 的行直接放在带有 id 的行下面,因此 理想情况下 排序顺序如下所示:

id title order parent_id
107fa138 video 0 NULL
8eeda86c mn 2 NULL
b45dc24d another 1 8eeda86c
d3490141 hello 9 8eeda86c
cac640ad xxe title 3 NULL
1ce4d070 sdfsdfsdf 4 NULL

我什至不知道我会怎么做。如果有人能给我指出正确的方向,那就太棒了。

我认为你的问题出在这里:

order by `order` AND COALESCE(`parent_id`, `order`), ...

这可能不是您认为的那样。 AND 是一个布尔运算符,所以就好像你写了这个表达式:

order by (`order` > 0) AND (COALESCE(`parent_id`, `order`) > 0), ...

也就是说,如果 order 和另一项都非零,则为 1,否则为 0。

我认为以下内容会更接近您的描述:

order by COALESCE(`parent_id`, `id`), 
    `parent_id` is not null, 
    `order`

演示:

create table pages ( id varchar(10) primary key, title text, `order` int, parent_id varchar(10) );  

insert into pages (id, title, `order`, parent_id) values 
('107fa138', 'video',     0, NULL),
('8eeda86c', 'mn',        2, NULL),
('cac640ad', 'xxe title', 3, NULL),
('1ce4d070', 'sdfsdfsdf', 4, NULL),
('b45dc24d', 'another',   1, '8eeda86c'),
('d3490141', 'hello',     9, '8eeda86c');

select `id`, `title`, 
  COALESCE(parent_id, id) as cpi, 
  parent_id is not null as pinn, 
  `order`, 
  `parent_id` 
from pages 
order by COALESCE(`parent_id`, `id`), `parent_id` is not null, `order`

+----------+-----------+----------+------+-------+-----------+
| id       | title     | cpi      | pinn | order | parent_id |
+----------+-----------+----------+------+-------+-----------+
| 107fa138 | video     | 107fa138 |    0 |     0 | NULL      |
| 1ce4d070 | sdfsdfsdf | 1ce4d070 |    0 |     4 | NULL      |
| 8eeda86c | mn        | 8eeda86c |    0 |     2 | NULL      |
| b45dc24d | another   | 8eeda86c |    1 |     1 | 8eeda86c  |
| d3490141 | hello     | 8eeda86c |    1 |     9 | 8eeda86c  |
| cac640ad | xxe title | cac640ad |    0 |     3 | NULL      |
+----------+-----------+----------+------+-------+-----------+

通过添加显示排序表达式的列,我们可以看到排序是如何发生的。

首先它按 cpi 字母顺序排序。这更喜欢 parent_id 如果它被设置,但默认为 id.

对于 cpi 的关系,则按 pinn 排序。所以 0 在 1 之前。

对于 pinn 的关系(即当多行的值为 1 时),则按 order.

排序

这不是你想要的吗?