使用 WITH 和 UNION 在 SQL 中检索时如何过滤结果

How to filter results when retrieving in SQL using WITH and UNION

我有一段代码,我不知道这里发生了什么,SQL-wise。代码如下:

WITH t ( clientId, code, cname, rootId, active ) 
AS 
(
SELECT clientID, code, cName, clientID AS rootId, active FROM clients AS [mt] WHERE [sub] = 0 
UNION ALL SELECT mt.clientID, mt.code, mt.cName, t.[rootId], mt.active FROM clients AS [mt] INNER JOIN t ON t.clientId = mt.[sub]
), 

roots AS (SELECT rootId FROM t WHERE cname LIKE '%abb%' OR code LIKE '%abb%') 

SELECT [t].[code], [t].[cname], [t].[clientID] FROM t 
INNER JOIN roots rt ON [rt].[rootId] = [t].[rootId] WHERE [t].active='True'

此代码工作正常,但我被要求更改它。在客户端 table 中,有一个名为 isParent 的新位字段。我只需要在 isParent='False' 时显示结果。目前,我得到以下列:

code.    cName.    clientID

我已经尝试了很多不同的方法来附加“AND isParent='False'”,但我总是收到一个错误,指出“t”中的列太少。任何帮助是极大的赞赏。谢谢!

代码正在客户端上执行分层递归 table。条件 isParent='False' 似乎表明您正试图从递归的基础中删除 non-root 行。所以我只将条件添加到顶部 SELECT 语句(在 UNION ALL 之上)。此外,我删除了不必要的括号并重新格式化了代码以提高可读性(至少在我看来)。

with 
t(clientid, code, cname, rootid, active) as (
    select clientid, code, cname, clientid as rootid, active 
    from clients mt
    where sub = 0 
          and isParent='False'
    union all
    select mt.clientid, mt.code, mt.cname, t.rootid, mt.active 
    from clients mt 
         join t on t.clientid = mt.sub), 
roots(rootid) as (
    select rootid 
    from t
    where cname like '%abb%' 
          or code like '%abb%') 
select t.code, t.cname, t.clientid 
from t 
     join roots rt on rt.rootid = t.rootid 
where t.active='true';