Sql父子查询不起作用
Posted
技术标签:
【中文标题】Sql父子查询不起作用【英文标题】:Sql parent Child Query not working 【发布时间】:2015-11-13 06:08:04 【问题描述】:我想获取父母和他们的孩子数据,意味着先来父母然后他们的孩子,下面是我想转换为父母和他们的孩子的查询
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'.
然后我更改我的查询并删除计数(*)
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'.
【问题讨论】:
【参考方案1】:其实是设计的,看Guidelines for Defining and Using Recursive Common Table Expressions
以下项目是不允许在一个 CTE_query_definition 递归成员:
选择不同的 分组依据 有 标量聚合 顶部 左、右、外连接(允许内连接) 子查询
您必须将 LEFT JOIN 和 COUNT 从 CTE 查询中移出,将这些数据存储在其他地方(例如临时表中),然后将这些数据与 CTE 查询的结果一起使用。或者您可以避免 CTE 查询,并为每个父子级别分别执行此操作,存储在单独的临时表中并使用结果。希望对您有所帮助。
【讨论】:
顺便说一句,在这里找到类似的东西:***.com/questions/9126704/… 您可以尝试将 LEFT JOIN 替换为 OUTER APPLY。以上是关于Sql父子查询不起作用的主要内容,如果未能解决你的问题,请参考以下文章
相同查询的 Spark sql 版本不起作用,而普通 sql 查询则起作用