Home > Database > Mysql Tutorial > sql 多级分类的级联查询

sql 多级分类的级联查询

WBOY
Release: 2016-06-07 17:49:18
Original
3366 people have browsed it

分类是在一般系统最常见的信息组织方式,有单级的分类,二级的分类,还有无限制级的分类。

当然我们给博客贴上分类的时候只要join下就可以找到分类的名称。

但是我们在做导航或者选择分类的时候往往涉及到分类的级联查询。下面就是说如何用sql查询这样的分类信息。

7 -- 建立分类表 

 代码如下 复制代码

CREATE TABLE t_category
(
    ID INT IDENTITY(1,1) PRIMARY KEY,
    Name VARCHAR(40) NOT NULL,
    ParentID INT DEFAULT(-1)
)

 

?-- 插入一些测试数据 
INSERT INTO t_category(name) VALUES('计算机类')
INSERT INTO t_category(name) VALUES('吃的类')
INSERT INTO t_category(name, parentid) VALUES('linux', 1)
INSERT INTO t_category(name, parentid) VALUES('python', 1)
INSERT INTO t_category(name, parentid) VALUES('oracle', 1)
INSERT INTO t_category(name, parentid) VALUES('水果', 2)
INSERT INTO t_category(name, parentid) VALUES('主食', 2)
INSERT INTO t_category(name, parentid) VALUES('米饭', 7)
INSERT INTO t_category(name, parentid) VALUES('面食', 7)
INSERT INTO t_category(name, parentid) VALUES('django', 4)
INSERT INTO t_category(name, parentid) VALUES('tornado', 4)

  

?-- 问题一:如何检索一个分类的路线 即:父->子->子->子 获得这样一个路径
-- 查询django分类的路径 结果应该为计算机类->python->django  
 

 代码如下 复制代码
WITH ctetable(id,name,pid) as (
    SELECT ID,name, parentid FROM t_category WHERE ID = 10
    UNION ALL
    SELECT p2.id, p2.name, parentid FROM ctetable JOIN t_category p2 ON p2.id =ctetable.pid 
)
SELECT * FROM ctetable ORDER BY ID

  

?-- 输出结果 
1, '计算机类', -1
4, 'python', 1
10, 'django', 4

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template