Home Database Mysql Tutorial sql多级分类汇总实现介绍

sql多级分类汇总实现介绍

Jun 07, 2016 pm 05:49 PM
Multi-level classification

本文章介绍了关于sql多级分类汇总实现方法及数据结构,有碰到问题的同学可参考一下。

据库结构如下
类别表
分类id 上级分类id 分类名称 分类级别 排序值

 代码如下 复制代码
id parentid categoryname categorylevel ordering
1   null      c1            1           1
2    1        c11           2           1
3    1        c12           2           2
4    1        c13           2           3
5    1        c14           2           4
6    2        c111          3           1
7    2        c112          3           2

然后 内容表是
内容id 类别id .........

 代码如下 复制代码
id categoryid .........
1    1       ........
2    4       ........
3    5       ........


这样处理的弊端是:如果数据量大,子分类很多,达到4级以上,这方法处理极端占用连接池
对性能影响很大。

如果用SQL下面的CTE递归处理的话,一次性就能把结果给查询出来,而且性能很不错
比用程序处理(数据量很大的情况),临时表性能更好,更方便 

 代码如下 复制代码
with area as(
select *,id px,cast(id as nvarchar(4000)) px2 from region where parentid=0
union all
select a.*,b.px,b.px2+ltrim(a.region_id) from region a join area b on a.parentid=b.id
)select * from area px,px2


可以查询出结果—-所有分类及相应分类下子分类

 代码如下 复制代码
id title parentid
1 广东省 0
2 广州 1
3 白云区 2
4 深圳 1
5 湖南省 0
6 长沙 5
7 株洲 5
 代码如下 复制代码


with area as(
select * from region where parentid=1
union all
select a.* from region a join area b on a.parentid=b.id
)select * from area

可以查询出结果—-指定分类及相应分类下子分类
id title parentid
1 广东省 0
2 广州 1
3 白云区 2


实现程序

 代码如下 复制代码

/*
标题:查询指定节点及其所有子节点的函数
作者:爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开)
时间:2008-05-12
地点:广东深圳
*/

create table tb(id varchar(3) , pid varchar(3) , name varchar(10))
insert into tb values('001' , null  , '广东省')
insert into tb values('002' , '001' , '广州市')
insert into tb values('003' , '001' , '深圳市')
insert into tb values('004' , '002' , '天河区')
insert into tb values('005' , '003' , '罗湖区')
insert into tb values('006' , '003' , '福田区')
insert into tb values('007' , '003' , '宝安区')
insert into tb values('008' , '007' , '西乡镇')
insert into tb values('009' , '007' , '龙华镇')
insert into tb values('010' , '007' , '松岗镇')
go

--查询指定节点及其所有子节点的函数
create f_cid(@ID varchar(3)) returns @t_level table(id varchar(3) , level int)
as
begin
  declare @level int
  set @level = 1
  insert into @t_level select @id , @level
  while @@ROWCOUNT > 0
  begin
    set @level = @level + 1
    insert into @t_level select a.id , @level
    from tb a , @t_Level b
    where a.pid = b.id and b.level = @level - 1
  end
  return
end
go

--调用函数查询001(广东省)及其所有子节点
select a.* from tb a , f_cid('001') b where a.id = b.id order by a.id
/*
id   pid  name      
---- ---- ----------
001  NULL 广东省
002  001  广州市
003  001  深圳市
004  002  天河区
005  003  罗湖区
006  003  福田区
007  003  宝安区
008  007  西乡镇
009  007  龙华镇
010  007  松岗镇

(所影响的行数为 10 行)
*/

--调用函数查询002(广州市)及其所有子节点
select a.* from tb a , f_cid('002') b where a.id = b.id order by a.id
/*
id   pid  name      
---- ---- ----------
002  001  广州市
004  002  天河区

(所影响的行数为 2 行)
*/

--调用函数查询003(深圳市)及其所有子节点
select a.* from tb a , f_cid('003') b where a.id = b.id order by a.id
/*
id   pid  name      
---- ---- ----------
003  001  深圳市
005  003  罗湖区
006  003  福田区
007  003  宝安区
008  007  西乡镇
009  007  龙华镇
010  007  松岗镇

(所影响的行数为 7 行)
*/

drop table tb
drop function f_cid

 

实例2

 

 代码如下 复制代码

t1
id     parentid
m    a
n    a
e    m
f    m
x    f
y    f
z    b

t2
row    id      amount
1    a    13.00
2    b    20.00
3    e    20.00
4    f    20.00
5    x    20.00
6    y    20.00
7    z    20.00
8    e    12.00
9    x    11.00
10    f    13.00

如何得出如下结果:

row     id      amount
7    x    20.00
11    x    11.00
    x小计    31.00
8    y    20.00
    y小计    20.00
6    f    20.00
12    f    13.00
    f小计    84.00
5    e    20.00
10    e    12.00
    e小计    32.00
3    m    14.00
    m小计    130.00
4    n    13.00
    n小计    13.00
1    a    13.00
    a小计    156.00
9    z    20.00
    z小计    20.00
2    b    20.00
    b小计    40.00
    总计    196.00

实现程序

-- 示例数据
 CREATE TABLE t1(
  id char(1),
  parentid char(1)
 );
 INSERT t1
 SELECT 'm', 'a' UNION ALL
 SELECT 'n', 'a' UNION ALL
 SELECT 'e', 'm' UNION ALL
 SELECT 'f', 'm' UNION ALL
 SELECT 'x', 'f' UNION ALL
 SELECT 'y', 'f' UNION ALL
 SELECT 'z', 'b';
 
 CREATE TABLE t2(
  row int,
  id char(1),
  amount decimal(10, 2)
 );
 INSERT t2
 SELECT '1', 'a', '13.00' UNION ALL
 SELECT '2', 'b', '20.00' UNION ALL
 SELECT '3', 'e', '20.00' UNION ALL
 SELECT '4', 'f', '20.00' UNION ALL
 SELECT '5', 'x', '20.00' UNION ALL
 SELECT '6', 'y', '20.00' UNION ALL
 SELECT '7', 'z', '20.00' UNION ALL
 SELECT '8', 'e', '12.00' UNION ALL
 SELECT '9', 'x', '11.00' UNION ALL
 SELECT '10', 'f', '13.00';
 GO
 
 -- 统计
 -- 逐级汇总
 declare @l int
 set @l=1
 
 select 
  A.[id],
  [pid] = A.parentid,
  [sumnum] = SUM(B.amount),
     level=case 
         when exists(select * from t1 where parentid=a.[id])
         then @l-1 else @l end
 into [#]
 from t1 A
  LEFT JOIN t2 B
   ON A.id = B.id
 GROUP BY A.id, A.parentid;
 
 if @@row/42852.htm target=_blank >count>0
     create index IDX_#_id_pid on [#]([id],[pid])
 else
     set @l=999
 
 while @@rowcount>0 or @l=1
 begin
     set @l=@l+1
     update a set level=@l,[sumnum]=isnull(a.[sumnum],0)+isnull(b.[sumnum],0)
     from [#] a,(
         select aa.pid,[sumnum]=sum(aa.[sumnum])
         from [#] aa,(
             select distinct [pid] from [#]
             where level=@l-1
         )bb where aa.[pid]=bb.[pid]
             AND NOT EXISTS(
                 SELECT * FROM [#] WHERE [PID]=aa.[PID] AND [Level]=0)
         GROUP BY aa.[PID]
         having sum(case when aa.level=0 then 1 else 0 end)=0
     )b where a.[id]=b.[pid]
 end
 
 -- 最终结果
 SELECT
  row = CASE
    WHEN GROUPING(A.row) = 0 THEN RTRIM(A.row)
    ELSE N''
   END,
  id = CASE
    WHEN GROUPING(A.row) = 0 THEN A.id
    WHEN GROUPING(A.id) = 0 THEN A.id + '小计'
    ELSE N'总计'
   END,
  amount = CASE
     WHEN GROUPING(A.row) = 0 THEN SUM(A.amount)
     WHEN GROUPING(A.id) = 0 THEN ISNULL((SELECT SUM(B.sumnum) FROM # B WHERE A.id = B.id), SUM(A.amount))
     ELSE SUM(A.amount)
    END
 FROM t2 A
 GROUP BY A.id, A.row WITH ROLLUP;
 drop table [#]
 GO
 
 DROP TABLE t1, t2;
 
 /*-- 结果
 row          id                                     amount
 ------------ ----- ---------------------------------------
 1            a                                       13.00
              a小计                                     13.00
 2            b                                       20.00
              b小计                                     20.00
 3            e                                       20.00
 8            e                                       12.00
              e小计                                     32.00
 4            f                                       20.00
 10           f                                       13.00
              f小计                                     84.00
 5            x                                       20.00
 9            x                                       11.00
              x小计                                     31.00
 6            y                                       20.00
              y小计                                     20.00
 7            z                                       20.00
              z小计                                     20.00
              总计                                     169.00
 
 (18 行受影响)
 --*/ 

性能分析:
对于一个3500条地区记录的数据表,其中有省,市,县3级
查询用时要1秒,视觉上感觉有点点慢,但不影响
数据量不大的分类,使用绝对无压力

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you alter a table in MySQL using the ALTER TABLE statement? How do you alter a table in MySQL using the ALTER TABLE statement? Mar 19, 2025 pm 03:51 PM

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

Explain InnoDB Full-Text Search capabilities. Explain InnoDB Full-Text Search capabilities. Apr 02, 2025 pm 06:09 PM

InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

How do I configure SSL/TLS encryption for MySQL connections? How do I configure SSL/TLS encryption for MySQL connections? Mar 18, 2025 pm 12:01 PM

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? Mar 21, 2025 pm 06:28 PM

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

How do you handle large datasets in MySQL? How do you handle large datasets in MySQL? Mar 21, 2025 pm 12:15 PM

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

Difference between clustered index and non-clustered index (secondary index) in InnoDB. Difference between clustered index and non-clustered index (secondary index) in InnoDB. Apr 02, 2025 pm 06:25 PM

The difference between clustered index and non-clustered index is: 1. Clustered index stores data rows in the index structure, which is suitable for querying by primary key and range. 2. The non-clustered index stores index key values ​​and pointers to data rows, and is suitable for non-primary key column queries.

How do you drop a table in MySQL using the DROP TABLE statement? How do you drop a table in MySQL using the DROP TABLE statement? Mar 19, 2025 pm 03:52 PM

The article discusses dropping tables in MySQL using the DROP TABLE statement, emphasizing precautions and risks. It highlights that the action is irreversible without backups, detailing recovery methods and potential production environment hazards.

How do you create indexes on JSON columns? How do you create indexes on JSON columns? Mar 21, 2025 pm 12:13 PM

The article discusses creating indexes on JSON columns in various databases like PostgreSQL, MySQL, and MongoDB to enhance query performance. It explains the syntax and benefits of indexing specific JSON paths, and lists supported database systems.

See all articles