2013-01-18 53 views
0

我有一個簡單的SQL查詢來計算就像在一個部門中的所有員工(兒童中):子查詢與子句中H2DB

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 
) 

但我給一個錯誤「的StackOverflow」,我不知道在哪裏是錯誤的,你能幫助我嗎? 存在用於測試情況下,一些數據: 表部:

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

表EMPLOYEE:

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

因此,當我在一處(A)選擇Eployee的量 - >結果:3,如果部門B - >結果:1​​ 謝謝!

+0

您可以包括一些數據一樣,所以我們有一個重現的測試案例? –

+0

謝謝托馬斯!我在答案中導入了一些數據,你能告訴我嗎? –

回答

1

我想我有一個可行的解決方案:

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; 
+0

謝謝托馬斯,我把我的帖子移到我的問題。我解決了這個問題,再次感謝! –

+0

我想如果Temp裏面的子查詢 - >它不起作用,但是外部查詢它的工作,對吧? –

+0

其實我不確定爲什麼你的查詢不起作用,我很抱歉... –