Sub Query with WITH-CLAUSE in H2DB

依然范特西╮ 提交于 2019-12-12 03:30:11

问题


I have a simple SQL query to count all Employees in a Department(within children) like:

With Temp(id) AS
(
        Select d.id From DEPARTMENT d 
    Where d.id = 1 
    UNION ALL
    Select d.id From DEPARTMENT d JOIN Temp te ON d.idDepartment = te.id
)
Select count(*) From 
(
    Select e.id From Employee e Join Temp te On e.idDepartment = te.id
)

But i give a error "StackOverflow", I dont know where is mistake, can you help me? there are some data for test case: Table Department :

ID----------departmentName-----------idDepartment(id parent)
1              A                         0
2              B                         1

Table Employee :

id----------employeeName------------idDepartment
1              E_1                       1
2              E_2                       1
3              E_3                       2

So when I select quantity of Eployee in a Department(A)--> result : 3, if Department B --> result: 1 Thanks!


回答1:


I think I have a solution that works:

create table Department(id int, name varchar(255), idDepartment int);
create table Employee(id int, name varchar(255), idDepartment int);
insert into Department values(1, 'A', 0), (2, 'B', 1);
insert into Employee values(1, 'E1', 1), (2, 'E2', 1), (3, 'E3', 2);
with recursive temp(id) as (
    select 1 union all
    select d.id from temp te 
    inner join Department d on d.idDepartment = te.id
)
select count(*) from temp te 
inner join Employee e on e.idDepartment = te.id;
drop table Department;
drop table Employee;


来源:https://stackoverflow.com/questions/14391406/sub-query-with-with-clause-in-h2db

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!