[英]Sql parent Child Query not working
我想获取父母及其子女的数据,意味着首先要成为父母,然后是他们的子女,以下是我要转换为父母及其子女的查询
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'
我在下面查询
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'.
实际上,这是设计使然 ,请阅读《定义和使用递归公用表表达式的准则》。
递归成员的CTE_query_definition中不允许以下各项:
- 选择地区
- 通过...分组
- HAVING
- 标量聚集
- 最佳
- 左,右,外联接(允许内联接)
- 子查询
您必须将LEFT JOIN和COUNT移出CTE查询,将这些数据存储在其他位置(例如在临时表中),然后再将它们与CTE查询的结果一起使用。 或者,您可以避免CTE查询,并针对每个级别的父子对象分别进行此步骤,将其存储在单独的临时表中并使用结果。 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.