我想得到父母和他们的孩子数据,意味着先来父母然后他们的孩子,下面是我想要转换为父母和他们的孩子的查询
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'.
答案 0 :(得分:0)
实际上它是按设计,阅读Guidelines for Defining and Using Recursive Common Table Expressions
以下项目不允许在a的CTE_query_definition中 递归成员:
- SELECT DISTINCT
- GROUP BY
- HAVING
- 标量聚合
- TOP
- LEFT,RIGHT,OUTER JOIN(允许内部联接)
- 子查询
您必须将您的LEFT JOIN和COUNT从CTE查询中移出,将这些数据存储在其他地方(例如在临时表中),然后再使用那些具有CTE查询结果的数据。或者,您可以避免CTE查询,并为每个级别的父级单独执行此操作,存储在单独的临时表中并使用结果。希望有所帮助。