2012-02-07 51 views
1

我有一個帶有父子關係和內容表的站點地圖表的CMS系統。有時我不想在查詢中包含內容,如果它是相應的站點地圖條目或其父母的任何一個被禁用。遞歸查詢來檢查所有父母是否已啓用

基本表的結構是:

tb_Sitemap:ID,PARENT_ID,啓用

tb_Content:ID,sitemap_id

所以我希望能夠添加一些我的查詢像這樣:

SELECT * FROM tb_Content WHERE {tb_Sitemap.enabled and any or all parents are also enabled} 

我知道我需要使用CTE,但我不確定如何將這些添加到WHERE子句或如何去做。

我猜我需要做這樣的事情,但不知道如何添加到WHERE子句:

;WITH cte (enabled) 
AS 
(
SELECT enabled FROM tb_Content WHERE id = tb_Content.sitemap_id 
UNION ALL 
SELECT CASE WHEN b.enabled != 1 THEN 0 ELSE a.enabled FROM tb_Sitemap a 
INNER JOIN cte b ON a.parent_id = b.id 
) 
SELECT enabled FROM cte 

的樣本數據:

tb_Sitemap

  • ID:1,PARENT_ID :null,已啓用:1
  • id:2,parent_id:1,enabled:1
  • id:3,parent _id:2,使能:1
  • ID:4,PARENT_ID:1,使能:0
  • ID:5,PARENT_ID:4,使能:1
  • ID:6,PARENT_ID:5,啓用:1

tbl_Content

  • sitemap_id:3(這似乎是因爲sitemap_id:3的啓用方式是所有的家長)
  • sitemap_id:6(這將不會出現,因爲雖然sitemap_id:6被啓用,其中之一其父母是不是)
+0

你想以某種方式做更多的事情,比如'SELECT FROM tb_Content WHERE啓用,NOT EXISTS(任何父被禁用)'我懷疑......你能表現出一定的樣本數據和期望的結果(例如,顯示應包含和排除的兩行)? – 2012-02-07 23:30:17

回答

4
-- A little test data. 
declare @tb_Sitemap as table (id int, parent_id int null, enabled bit) 
insert into @tb_Sitemap (id, parent_id, enabled) values 
    (1, NULL, 1), (2, 1, 1), (3, 2, 1), 
    (4, 1, 0), (5, 4, 1), (6, 5, 1) 
declare @tb_Content as table (sitemap_id int) 
insert into @tb_Content (sitemap_id) values (3), (6) 

-- Query the little beggars. 
; with CTE as (
    -- Start at the root(s). 
    select id, parent_id, enabled, enabled as summary_enabled 
    from @tb_Sitemap 
    where parent_id is NULL 
    union all 
    -- Add one generation at a time. 
    select S.id, s.parent_id, s.enabled, cast(case when s.enabled = 1 and CTE.summary_enabled = 1 then 1 else 0 end as bit) 
    from CTE inner join 
     @tb_Sitemap as S on S.parent_id = CTE.id 
) 
select *, case when summary_enabled = 1 and sitemap_id is not NULL then '< winner!' else '' end as include 
    from CTE left outer join 
    @tb_Content as C on C.sitemap_id = CTE.id 
+0

這似乎是做這項工作。我只是改變了查詢的最後部分,以得到我想要的:從CTE內部連接@ tb_Content中選擇C. *,CTE.summary_enabled作爲C. on C.sitemap_id = CTE.id其中CTE.summary_enabled = 1 – johna 2012-02-09 02:15:48