--
-- 表的结构 `my_class`
--CREATE TABLE IF NOT EXISTS `my_class` (
`id` smallint(5) unsigned NOT NULL auto_increment,
`parentid` smallint(5) unsigned NOT NULL,
`classname` varchar(20) character set gb2312 NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;--
-- 导出表中的数据 `my_class`
--INSERT INTO `my_class` (`id`, `parentid`, `classname`) VALUES
(1, 0, '中国'),
(2, 1, '江苏'),
(3, 2, '苏州'),
(4, 2, '南京'),
(5, 1, '河南'),
(6, 5, '郑州'),
(7, 5, '洛阳'),
(8, 0, '美国'),
(9, 8, '加州'),
(10, 9, '圣路易斯'),
(11, 9, '萨克拉门托');
有一个表 id parentid name 这3个字段 parentid 分别是ID 的上一级的ID 如何找出所有最后一级的所有信息~!??
SOS.........知道的朋友帮忙回答 万分感谢
-- 表的结构 `my_class`
--CREATE TABLE IF NOT EXISTS `my_class` (
`id` smallint(5) unsigned NOT NULL auto_increment,
`parentid` smallint(5) unsigned NOT NULL,
`classname` varchar(20) character set gb2312 NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;--
-- 导出表中的数据 `my_class`
--INSERT INTO `my_class` (`id`, `parentid`, `classname`) VALUES
(1, 0, '中国'),
(2, 1, '江苏'),
(3, 2, '苏州'),
(4, 2, '南京'),
(5, 1, '河南'),
(6, 5, '郑州'),
(7, 5, '洛阳'),
(8, 0, '美国'),
(9, 8, '加州'),
(10, 9, '圣路易斯'),
(11, 9, '萨克拉门托');
有一个表 id parentid name 这3个字段 parentid 分别是ID 的上一级的ID 如何找出所有最后一级的所有信息~!??
SOS.........知道的朋友帮忙回答 万分感谢
+----+----------+------------+
| id | parentid | classname |
+----+----------+------------+
| 1 | 0 | 中国 |
| 2 | 1 | 江苏 |
| 3 | 2 | 苏州 |
| 4 | 2 | 南京 |
| 5 | 1 | 河南 |
| 6 | 5 | 郑州 |
| 7 | 5 | 洛阳 |
| 8 | 0 | 美国 |
| 9 | 8 | 加州 |
| 10 | 9 | 圣路易斯 |
| 11 | 9 | 萨克拉门托 |
+----+----------+------------+
11 rows in set (0.00 sec)mysql> select * from my_class t where not exists (select 1 from my_class where p
arentid=t.id);
+----+----------+------------+
| id | parentid | classname |
+----+----------+------------+
| 3 | 2 | 苏州 |
| 4 | 2 | 南京 |
| 6 | 5 | 郑州 |
| 7 | 5 | 洛阳 |
| 10 | 9 | 圣路易斯 |
| 11 | 9 | 萨克拉门托 |
+----+----------+------------+
6 rows in set (0.00 sec)
mysql> select a.*
-> from my_class a left join my_class b on a.id=b.parentid
-> where b.id is null;
+----+----------+------------+
| id | parentid | classname |
+----+----------+------------+
| 3 | 2 | 苏州 |
| 4 | 2 | 南京 |
| 6 | 5 | 郑州 |
| 7 | 5 | 洛阳 |
| 10 | 9 | 圣路易斯 |
| 11 | 9 | 萨克拉门托 |
+----+----------+------------+
6 rows in set (0.06 sec)mysql>
6 rows in set (0.00 sec)mysql>