WEB开发网
开发学院数据库MSSQL Server 层次结构的数据库处理 阅读

层次结构的数据库处理

 2010-03-12 00:00:00 来源:WEB开发网   
核心提示: 查询所有的叶子节点 我们可以使用左连接(LEFT JOIN)查询来获得所有的叶子节点(叶子节点:无子节点的节点)SELECTt1.nameFROMcategoryASt1LEFTJOINcategoryast2ONt1.category_id=t2.parentWHEREt2.category_

查询所有的叶子节点

我们可以使用左连接(LEFT JOIN)查询来获得所有的叶子节点(叶子节点:无子节点的节点)

SELECT t1.name FROM
category AS t1 LEFT JOIN category as t2
ON t1.category_id = t2.parent
WHERE t2.category_id IS NULL;

+--------------+
| name         |
+--------------+
| TUBE         |
| LCD          |
| PLASMA       |
| FLASH        |
| CD PLAYERS   |
| 2 WAY RADIOS |
+--------------+

获得单条路径

自连接也可以获得一条完整的节点关系路径。

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' AND t4.name = 'FLASH';
+-------------+----------------------+-------------+-------+
| lev1        | lev2                 | lev3        | lev4  |
+-------------+----------------------+-------------+-------+
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS | FLASH |
+-------------+----------------------+-------------+-------+
1 row in set (0.01 sec)

上一页  1 2 3 4 5 6 7 8  下一页

Tags:层次 结构 数据库

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接