2013-06-28 43 views
2

我有兩個表一個是category和另一個是sub-category。那兩張桌子被分配給FK許多桌子。在某些情況下,我們會將子類別的一條記錄移至主類別。所以此時出現約束錯誤,因爲與其他表關聯。所以我不會創建這個架構如何爲以下情況創建模式?

所以現在我打算創建類別,在同一個表和子類創建關係表,使它們之間的關係。

category table:

id(PK,AUTO Increment), 
item===>((1,phone),(2.computer),(3,ios),(4,android),(5,software),(6,hardware)). 

relationship table:

id,cate_id(FK), 
parentid(refer from category table)===>((1,1,0),(2,2,0),(3,3,1), 
             (4,4,1),(5,5,2),(5,5,3)). 

在我的身邊wouldnot去層級多於三個。

如果我們輕鬆地將子類別移到主類別ex:(4,4,1) to (4,4,0)而不影響任何其他表格。這是一個好程序嗎?

如果我們將保持數百萬條記錄,將來我們會面對其他任何問題嗎?

有任何其他想法意味着讓我知道?

回答

1

如果您在樹中有多個級別,並且想要查找任何類別的所有子類別,則可能存在問題。這將需要多個查詢或遞歸的查詢。

您可以改爲查看"Nested Sets"數據結構。它支持有效查詢任何子樹。它有一個昂貴的更新,但更新可能不會經常發生。如果需要,您可以批量更新並在夜間運行它們。

create table Category (
    Id int not null primary key auto_increment, 
    LeftExtent int not null, 
    RightExtent int not null, 
    Name varchar(100) not null 
); 

create table PendingCategoryUpdate (
    Id int not null primary key auto_increment, 
    ParentCategoryId int null references Category (Id), 
    ParentPendingId int null references PendingCategoryUpdate (Id), 
    Name varchar(100) not null 
); 

如果你有一個小數目的類別,一個正常的家長參考應該夠了。您甚至可以將類別讀入內存中進行處理。

create table Category (
    Id int not null primary key auto_increment, 
    ParentId int null references Category (Id), 
    Name varchar(100) not null 
); 

-- Just an example 
create table Record (
    Id int not null primary key auto_increment, 
    CategoryId int not null references Category (Id) 
); 

select * 
from Record 
where CategoryId in (1, 2, 3); -- All the categories in the chosen sub-tree 
0

如何創建一個表如下:

categories(
    id int not null auto_increment primary key, 
    name char(10), 
    parent_id int not null default 0) 

凡PARENT_ID是一個FK的ID,它是表的PK。 當parent_id爲0時,這個類別是主類別。當它大於0時,這是該父級的子類別。 要查找某個類別的父級,您將執行自聯接。

相關問題