本人有二张表是栏目表,一个是栏目关系表名,channel, 有栏目ID和他的父栏目,另一个是表名称channel_name,有栏目ID和名称
CREATE TABLE `channel` ( `id` varchar(11) NOT NULL, `parent_id` varchar(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `channel_name` ( `id` varchar(11) NOT NULL, `c_name` varchar(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `channel` VALUES ("74", null); INSERT INTO `channel` VALUES ("75", null); INSERT INTO `channel` VALUES ("76", null); INSERT INTO `channel` VALUES ("77", null); INSERT INTO `channel` VALUES ("78", "74"); INSERT INTO `channel` VALUES ("79", "74"); INSERT INTO `channel` VALUES ("80", "75"); INSERT INTO `channel` VALUES ("81", "75"); INSERT INTO `channel` VALUES ("82", "77"); INSERT INTO `channel` VALUES ("83", "81"); INSERT INTO `channel` VALUES ("84", "81"); INSERT INTO `channel` VALUES ("85", "81"); INSERT INTO `channel` VALUES ("86", "81"); INSERT INTO `channel` VALUES ("87", null); INSERT INTO `channel` VALUES ("88", "76"); INSERT INTO `channel` VALUES ("89", "76"); INSERT INTO `channel` VALUES ("90", "76"); INSERT INTO `channel_name` VALUES ("74", "a74"); INSERT INTO `channel_name` VALUES ("75", "a75"); INSERT INTO `channel_name` VALUES ("76", "a76"); INSERT INTO `channel_name` VALUES ("77", "a77"); INSERT INTO `channel_name` VALUES ("78", "a78"); INSERT INTO `channel_name` VALUES ("79", "a79"); INSERT INTO `channel_name` VALUES ("80", "a80"); INSERT INTO `channel_name` VALUES ("81", "a81"); INSERT INTO `channel_name` VALUES ("82", "a82"); INSERT INTO `channel_name` VALUES ("83", "a83"); INSERT INTO `channel_name` VALUES ("84", "a84"); INSERT INTO `channel_name` VALUES ("85", "a85"); INSERT INTO `channel_name` VALUES ("86", "a86"); INSERT INTO `channel_name` VALUES ("87", "a87"; INSERT INTO `channel_name` VALUES ("88", "a88"); INSERT INTO `channel_name` VALUES ("89", "a89"); INSERT INTO `channel_name` VALUES ("90", "a90");
本人想得到的结果如下
一级 二级 三级 名称
74 78 a78
79 a79
75 80 a80
81 83 a83
84 a84
85 a85
86 a86
76 88 a88
89 a89
90 a90
77 82 a82
87 a87
上一问ACMAIN_CHM老师已经给了回答,但结果中没有最后一的一列
所以本人又问题了一次
解决方案
100
select o.id as 一级, t.id as 二级, w.id as 三级, (CASE WHEN n3.c_name is not null THEN n3.c_name WHEN n2.c_name is not null THEN n2.c_name WHEN n1.c_name is not null THEN n1.c_name END) 名称 from channel o LEFT JOIN channel_name n1 ON n1.id=o.id LEFT JOIN channel t ON t.parent_id=o.id LEFT JOIN channel_name n2 ON n2.id=t.id LEFT JOIN channel w ON w.parent_id=t.id LEFT JOIN channel_name n3 ON n3.id=w.id where o.parent_id is null order by o.id