层次结构的数据库处理
2010-03-12 00:00:00 来源:WEB开发网在这种邻接表模式下,表中每一个节点都包含一个指向父节点的指针。这个例子中的最顶层的元素,其父节点为NULL。邻接表模式的优点是很简单,很容易看清父子关系,例如 Flash 是 MP3 PLAYERS(MP3播放器)的子节点,MP3 PLAYERS是PORTABLE ELECTRONICS(便携式电子设备)的子节点,PORTABLE ELECTRONICS 又是 ELECTRONICS (电子设备)的子节点。 邻接表在客户端的代码上比较容易处理,但是后台的服务器要使用纯粹的SQL来工作是有问题的。
检索完整的树
处理层状数据时,首先遇到的常见任务是显示整个树,通常要求某种形式的缩进格式。使用SQL时一般的做法是采用自连接:
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = 'ELECTRONICS';
+-------------+----------------------+--------------+-------+
| lev1 | lev2 | lev3 | lev4 |
+-------------+----------------------+--------------+-------+
| ELECTRONICS | TELEVISIONS | TUBE | NULL |
| ELECTRONICS | TELEVISIONS | LCD | NULL |
| ELECTRONICS | TELEVISIONS | PLASMA | NULL |
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS | FLASH |
| ELECTRONICS | PORTABLE ELECTRONICS | CD PLAYERS | NULL |
| ELECTRONICS | PORTABLE ELECTRONICS | 2 WAY RADIOS | NULL |
+-------------+----------------------+--------------+-------+
6 rows in set (0.00 sec)
更多精彩
赞助商链接