示例 GROUP_CONCAT

example GROUP_CONCAT

我有一个包含两列(大小写和子大小写)的 table 以及以下值:

case subcase
1    0
2    1
3    1
4    0
5    0
6    4

我想要一个只有子案例的案例列表 喜欢:

case  list_of_subcase
1     2,3
4     6
5     0

案例 2、3 和 6 未列出,因为它们是子案例。

案例 5 没有子案例但不是子案例本身。

怎样写才合适select?有帮助吗?

这里的挑战是正确过滤——保留“5”,而不是其他子情况。

select (case when c.subcase = 0 then c.case else c.subcase) as subcase, 
       group_concat(c.case)
from cases c 
where c.subcase = 0 or
      (c.subcase = 0 and 
       not exists (select 1 from cases c2 where c2.subcase = c.case)
      )
group by (case when c.subcase = 0 then c.case else c.subcase end);

编辑:

使用 union all:

来表达可能更容易
select c.subcase, group_concat(c.case)
from cases c 
where c.subcase = 0 
group by c.subcase
union all
select c.case, 0
from cases c
group by c.case
having sum(c.subcase <> 0) = 0;

我们是否有考虑过度的危险...

DROP TABLE my_table;

CREATE TABLE my_table
(my_case INT NOT NULL
,subcase INT NULL
);

INSERT INTO my_table VALUES
(1    ,NULL),
(2    ,1),
(3    ,1),
(4    ,NULL),
(5    ,NULL),
(6    ,4);

SELECT x.my_case
     , GROUP_CONCAT(y.my_case) subcases 
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.subcase = x.my_case 
 WHERE x.subcase IS NULL 
 GROUP 
    BY x.my_case;
+---------+----------+
| my_case | subcases |
+---------+----------+
|       1 | 2,3      |
|       4 | 6        |
|       5 | NULL     |
+---------+----------+