2012-02-07 10 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、有効:1
  • id:3、parent _id:2、有効:1
  • 番号:4、PARENT_ID:1、有効:0
  • 番号:5、PARENT_ID:4、有効:PARENT_ID 6:1
  • 番号5、有効:1

tbl_Content

  • sitemap_id:3(sitemap_idので、これが表示されます:3は、その親のすべてであるとして有効になっている)6有効になっている:
  • sitemap_id:もののsitemap_idがあるため6(これは表示されません、 の一つ その親が `)私はあなたが何らかの形で有効になってAND NOTが(無効になっているいずれかの親をEXISTS tb_Contentから選ぶより`のような何かをしたい疑う)
+0

ではありません...あなたはいくつかのサンプルデータを表示することができますし、望ましい結果(例えば、含まれ、除外されるべき両方の行を表示する)? –

答えて

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.summary_enabled from CTE内部結合@ tb_Content CでC.sitemap_id = CTE.idどこCTE.summary_enabled = 1 – johna

関連する問題