如何在sql中过滤表数据

时间:2014-03-18 07:11:02

标签: sql common-table-expression

我使用此查询来过滤数据,但我得到了所有我不想要的数据。

我只想要节点及其子节点中的文本('接线端子和连接器','接口模块','开关模式电源','专业工具','标记和雕刻系统',' DIN导轨插座和开关')

WITH Nodes (NodeID,ParentID,NodeText)
AS
(
select ID,parentID,text 
from umbracoNode 
where text in ('Terminal Blocks & Connectors','Interface Modules','Switch-Mode Power Supply','Professional Tools','Marking and Engraving Systems','DIN Rail Socket and Switches')
union all
select ID,umbracoNode.parentid,TEXT 
from umbracoNode 
INNER JOIN Nodes on umbraconode.parentID=Nodes.NodeID
)
SELECT  * FROM Nodes

1 个答案:

答案 0 :(得分:0)

您已定义了递归CTE,但您希望限制递归。我通常通过计算我获得的深度并使用WHERE子句来指定限制来做到这一点:

WITH Nodes (NodeID,ParentID,NodeText,Depth)
AS
(
select ID,parentID,text,1 
from umbracoNode 
where text in ('Terminal Blocks & Connectors','Interface Modules',
               'Switch-Mode Power Supply','Professional Tools',
               'Marking and Engraving Systems','DIN Rail Socket and Switches')
union all
select ID,umbracoNode.parentid,TEXT,Depth+1 
from umbracoNode 
INNER JOIN Nodes on umbraconode.parentID=Nodes.NodeID
WHERE Depth <= 1
)
SELECT  * FROM Nodes

在这种情况下看起来微不足道,但很容易扩展到你想要的任何深度。