2
我希望得到家長和他們的孩子數據,意味着先到父母那麼他們的孩子的,下面是查詢,我要轉換爲父母和他們的孩子的Sql父子查詢不工作
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'.
然後我改變我的查詢d拔下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'.
順便說一句,在這裏找到類似的東西:http://stackoverflow.com/questions/9126704/why-cannot-we-use-outer-joins-in-recursive-cte/9126833#9126833 你可以嘗試更換左加入外部應用。 –