我先假设你是 Oracle 吧。
CREATE TABLE test_tree (
test_id INT NOT NULL,
pid INT,
test_val VARCHAR(10),
PRIMARY KEY (test_id)
);
INSERT INTO test_tree VALUES(1, NULL, 'NET');
INSERT INTO test_tree VALUES(2, 1, 'C#');
INSERT INTO test_tree VALUES(3, 1, 'J#');
INSERT INTO test_tree VALUES(4, 1, 'ASPNET');
INSERT INTO test_tree VALUES(5, 1, 'VBNET');
INSERT INTO test_tree VALUES(6, NULL, 'J2EE');
INSERT INTO test_tree VALUES(7, 6, 'EJB');
INSERT INTO test_tree VALUES(8, 6, 'Servlet');
INSERT INTO test_tree VALUES(9, 6, 'JSP');
INSERT INTO test_tree VALUES(10, NULL, 'Database');
INSERT INTO test_tree VALUES(11, 10, 'DB2');
INSERT INTO test_tree VALUES(12, 10, 'MySQL');
INSERT INTO test_tree VALUES(13, 10, 'Oracle');
INSERT INTO test_tree VALUES(14, 10, 'SQL Server');
INSERT INTO test_tree VALUES(15, 13, 'PL/SQL');
INSERT INTO test_tree VALUES(16, 15, 'Function');
INSERT INTO test_tree VALUES(17, 15, 'Procedure');
INSERT INTO test_tree VALUES(18, 15, 'Package');
INSERT INTO test_tree VALUES(19, 15, 'Cursor');
INSERT INTO test_tree VALUES(20, 14, 'T-SQL');
使用 START WITH CONNECT BY 语句实现树状查询
通过根节点 向下查询子节点
SELECT
LPAD(' ', 2(LEVEL-1)) || test_val AS test_val
FROM
test_tree
START WITH
test_id IN (1, 6, 10)
CONNECT BY PRIOR test_id = pid;
TEST_VAL
-----------------------------------------------------------
NET
C#
J#
ASPNET
VBNET
J2EE
EJB
Servlet
JSP
Database
DB2
TEST_VAL
-----------------------------------------------------------
MySQL
Oracle
PL/SQL
Function
Procedure
Package
Cursor
SQL Server
T-SQL
20 rows selected简单分析了一下sql的结构,你的sql效率差的最大问题在于对每个b子查询中的记录都要start with遍历一次。
虽然没弄清楚你的表结构,但你可以尝试一下使用下面的方案解决;
1,将记录整理成如下形式
部门,科室,职位,人员
2, 然后使用
select 部门,科室,职位,count(人员)
group by rollup(部门,科室,职位)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)