H2DB 中带 WITH-CLAUSE 的子查询
Posted
技术标签:
【中文标题】H2DB 中带 WITH-CLAUSE 的子查询【英文标题】:Sub Query with WITH-CLAUSE in H2DB 【发布时间】:2013-01-18 02:09:21 【问题描述】:我有一个简单的 SQL 查询来计算部门中的所有员工(在孩子中),例如:
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
)
但是我给出一个错误“***”,我不知道哪里出错了,你能帮我吗? 测试用例有一些数据: 餐桌部门:
ID----------departmentName-----------idDepartment(id parent)
1 A 0
2 B 1
表员工:
id----------employeeName------------idDepartment
1 E_1 1
2 E_2 1
3 E_3 2
所以当我选择部门(A)中的员工数量时-->结果:3,如果B部门-->结果:1 谢谢!
【问题讨论】:
能否也包含一些数据,以便我们拥有可重现的测试用例? 感谢托马斯!我在回答中导入了一些数据,你能告诉我吗? 【参考方案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;
【讨论】:
感谢 Thomas,我将帖子移至我的问题。我解决了这个问题,再次感谢! 我认为如果 Temp inside sub query --> 它不工作,但在外部查询它工作,对吧?以上是关于H2DB 中带 WITH-CLAUSE 的子查询的主要内容,如果未能解决你的问题,请参考以下文章
Laravel 5.8,在 where 子句中带有 Count(*) 的棘手子查询
with-clause 在 hSQL 中引用了两个不同的 from-clause 元素