本人有二张表是栏目表,一个是栏目关系表名,channel, 有栏目ID和他的父栏目,另一个是表名称channel_name,有栏目ID和名称
CREATE TABLE `channel` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parent_id` int(11) DEFAULT NULL COMMENT "父栏目ID", ) 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"); CREATE TABLE `channel_name` ( `id` int(11) NOT NULL AUTO_INCREMENT, `c_name` int(11) DEFAULT NULL COMMENT "栏目名称", ) 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,a78
79 a79,a79
75 80 a80,a80
81 83 a81,a83
84 a84,a84
85 a85,a85
86 a86,a86
76 88 a88,a88
89 a89,a89
90 a90,a90
77 82 a82,a82
87 a87,a87
谢谢各位老师,可以加分
解决方案
100
mysql> select -> IF(t2.id is null,t1.id, -> if(t2.id=(select min(id) from channel where parent_id=t2.parent_id ) , -> t1.id, -> "" -> )) as d1, -> IFNULL(IF(t3.id is null,t2.id, -> if(t3.id=(select min(id) from channel where parent_id=t3.parent_id ) , -> t2.id, -> "" -> )),"") as d2, -> IFNULL(t3.id,"") as d3 -> from channel t1 left join channel t2 on t2.parent_id=t1.id -> left join channel t3 on t3.parent_id=t2.id -> where t1.parent_id is null -> order by t1.id,t2.id,t3.id; +--+--+--+ | d1 | d2 | d3 | +--+--+--+ | 74 | 78 | | | | 79 | | | 75 | 80 | | | | 81 | 83 | | | | 84 | | | | 85 | | | | 86 | | 76 | 88 | | | | 89 | | | | 90 | | | 77 | 82 | | | 87 | | | +--+--+--+ 12 rows in set (0.00 sec) mysql>