2011-03-17 113 views
0

我需要在SQL中實現如下分類:SQL:如何實現泛型類?

  • 組可以包含多個測試或多個(孩子)組
  • 測試可以在多個組
  • (子)組可以在多個(父)groups

...這意味着2 x M:N關係。下面的表格可以存儲組樹:

TEST_TABLE
爲test_id(PK),TEST_NAME

GROUP_TABLE
GROUP_ID(PK),組名

TEST_IN_GROUP_TABLE
爲test_id(FK ),group_id(fk)

GROUP_RELATIONS_TABLE
parent_group_id(FK),child_group_id(FK)

但是:

  • 如何列出組中的所有測試?這對我來說聽起來很難,因爲小組可能包含測試或其他測試的子小組。
  • 或者如何修改表以使這樣的SELECT成爲可能?我可以在GROUP_TABLE中創建更多child_count列。它將被觸發器自動填充。但即使如此,這對我來說也很難。
+0

哪個版本的SQL Server? – RichardTheKiwi 2011-03-17 07:30:48

+0

數據庫可能位於MS SQL Server 2008 R2上。 (我在邏輯模型中,我會稍後做物理模型)。 – jing 2011-03-17 07:37:58

+0

然後設計很好。測試組和1-M:M-1橋接表是正確的,層次表組關係也是如此。 – RichardTheKiwi 2011-03-17 07:40:48

回答

1

您可以使用公共表表達式首先建立所尋找的組的group_id,然後使用該單一的組列表通過TEST_IN_GROUP_TABLE連接到所有測試的測試表。

;with cte as (
    select group_id 
    from GROUP_TABLE 
    where group_id = 1 
    union all 
    select child_group_id 
    from GROUP_RELATIONS_TABLE 
    inner join cte on cte.group_id = GROUP_RELATIONS_TABLE.parent_group_id 
) 
select t.* 
from cte 
inner join TEST_IN_GROUP_TABLE tg on tg.group_id = cte.group_id 
inner join TEST_TABLE t on t.test_id = tg.test_id 
+0

我驗證了它,它的工作原理。謝謝。 – jing 2011-03-21 10:53:53