Sql父子查询不工作
本文关键字:工作 查询 父子 Sql | 更新日期: 2023-09-27 18:08:59
我想获得父母和他们的孩子的数据,意思是首先是父母,然后是他们的孩子,下面是查询,我想转换为父母和他们的孩子
SELECT a.FactorTitle,
a.FactorCode,
a.parentId,
c.FactorColumnCode,
c.FactorColumnTitle,
c.FactorColumnValue,
c.isFactorValue,
c.FieldType,
(SELECT count(*)
FROM FactorSetup
WHERE parentId=a.FactorCode) AS childCount
FROM FactorSetup a
INNER JOIN PDModelSetup b ON a.PDModelCode=b.PDModelCode
LEFT JOIN FactorColumnSetup c ON a.FactorCode=c.FactorCode
WHERE a.PDModelCode=2
AND c.isFactorValue <> 'Y'
AND a.FactorType='4'
I try below query
WITH EntityChildren AS
(
SELECT a.FactorTitle,
a.FactorCode,
a.parentId,
c.FactorColumnCode,
c.FactorColumnTitle,
c.FactorColumnValue,
c.isFactorValue,
c.FieldType,
(SELECT count(*)
FROM FactorSetup
WHERE parentId=a.FactorCode) AS childCount
FROM FactorSetup a
LEFT JOIN FactorColumnSetup c ON a.FactorCode=c.FactorCode
UNION ALL
SELECT a.FactorTitle,
a.FactorCode,
a.parentId,
c.FactorColumnCode,
c.FactorColumnTitle,
c.FactorColumnValue,
c.isFactorValue,
c.FieldType,
(SELECT count(*)
FROM FactorSetup
WHERE parentId=a.FactorCode) AS childCount
FROM FactorSetup a
INNER JOIN EntityChildren e2 ON a.parentId = e2.FactorCode
LEFT JOIN FactorColumnSetup c ON a.FactorCode=c.FactorCode
)
SELECT * FROM EntityChildren
在执行这些查询后,我得到了这个错误
Msg 467, Level 16, State 1, Line 1
GROUP BY, HAVING, or aggregate functions are not allowed in the recursive part of a recursive common table expression 'EntityChildren'.
Msg 462, Level 16, State 1, Line 1
Outer join is not allowed in the recursive part of a recursive common table expression 'EntityChildren'.
然后我改变我的查询并删除count(*)
WITH EntityChildren AS
(
SELECT a.FactorTitle,
a.FactorCode,
a.parentId,
c.FactorColumnCode,
c.FactorColumnTitle,
c.FactorColumnValue,
c.isFactorValue,
c.FieldType
FROM FactorSetup a
LEFT JOIN FactorColumnSetup c ON a.FactorCode=c.FactorCode
UNION ALL
SELECT a.FactorTitle,
a.FactorCode,
a.parentId,
c.FactorColumnCode,
c.FactorColumnTitle,
c.FactorColumnValue,
c.isFactorValue,
c.FieldType
FROM FactorSetup a
INNER JOIN EntityChildren e2 ON a.parentId = e2.FactorCode
LEFT JOIN FactorColumnSetup c ON a.FactorCode=c.FactorCode
)
SELECT * FROM EntityChildren
然后我得到了这个错误
Msg 462, Level 16, State 1, Line 1
Outer join is not allowed in the recursive part of a recursive common table expression 'EntityChildren'.
实际上这是设计的,请阅读定义和使用递归公共表表达式的指南
在a的CTE_query_definition中不允许下列项递归成员:
- 选择不同的
GROUP BY >- 在
<- 标量聚合/gh>
- 顶部
- 左,右,外连接(允许内连接)
- 子查询
您必须将LEFT join和COUNT移出CTE查询,将这些数据存储在其他地方(例如在临时表中),然后将它们与CTE查询的结果一起使用。或者,您可以避免CTE查询,并对父子级的每个级别分别执行此步骤,将其存储在单独的临时表中并使用结果。