search
HomeDatabaseMysql Tutorialsql多级分类汇总实现介绍

本文章介绍了关于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
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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment