分层查询将中级类别归类为顶级

时间:2019-04-29 23:06:10

标签: mysql sql

我有一个包含3级层次结构数据的表,但是我的查询错误地对这些级别进行了分类。

我的查询:

SELECT  t1.name AS lev1, t2.name as lev2, t3.name as lev3
FROM sds_test AS t1
LEFT JOIN sds_test AS t2 ON t2.parent_id = t1.ID
LEFT JOIN sds_test AS t3 ON t3.parent_id = t2.ID;

博物馆和艺术学校类别正在增加一排,因为它们是顶级类别,这是我要消除的东西。如果我将级别2设置为非NULL,它将把具有单个顶级级别的那些类别弄乱,例如航空

期望的结果博物馆和艺术学校不应是顶级类别,也不能为它们单独放置一行。

Actual Results Expected

我不确定如何解决此问题,因为CTE也在为我提供类似的结果。我尝试使用案例

case when parent_id = NULL then 再次没有给我想要的结果。

SQL查询以重新生成表:

create table sds_test (id int, name varchar(30), parent_id int);
insert into sds_test values(1, 'Educational Institute', NULL);
insert into sds_test values(2, 'Speciality Schools', 1);
insert into sds_test values(3, 'Arts School', 2);

insert into sds_test values(4, 'Restraunts', NULL);
insert into sds_test values(5, 'Asian Restraunts', 4);
insert into sds_test values(6, 'malasian Rest', 5);

insert into sds_test values(7, 'Recreational', NULL);
insert into sds_test values(8, 'Museum', 7);

insert into sds_test values(9, 'Aviation', NULL);

1 个答案:

答案 0 :(得分:0)

我认为您非常亲密:

SELECT  t1.name AS lev1, t2.name as lev2, t3.name as lev3
FROM sds_test AS t1
LEFT JOIN sds_test AS t2 ON t2.parent_id = t1.ID
LEFT JOIN sds_test AS t3 ON t3.parent_id = t2.ID
WHERE t1.parent_id IS NULL

导致:

lev1                    lev2                lev3    
Educational Institute   Speciality Schools  Arts School
Restraunts              Asian Restraunts    malasian Rest
Recreational            Museum              NULL
Aviation                NULL                NULL 

我所做的就是添加一个条件,即t1中的项目不应具有父项。

这显然与所需的输出不匹配。我想知道为什么航空不应该在那里?