我想通過使用幾乎多態的方法來解決這個問題。你可以只用兩個表,就像這樣:
CREATE TABLE Node (id UNIQUEIDENTIFIER NOT NULL, PRIMARY KEY (id));
CREATE TABLE Relationships (
parent UNIQUENIDENTIFIER NOT NULL,
child UNIQUEIDENTIFIER NOT NULL,
CONSTRAINT FK_Relationship_ParentNode
FOREIGN KEY (parent) REFERENCES Node(id),
CONSTRAINT FK_Relationship_ChildNode
FOREIGN KEY (child) REFERENCES Node(id)
);
那麼所有其他實體節點「繼承」:
CREATE TABLE Person (
id UNIQUEIDENTIFIER NOT NULL,
name NVARCHAR(50) NOT NULL,
CONSTRAINT FK_Person_Node
FOREIGN KEY (id) REFERENCES Node(id)
);
CREATE TABLE ParkingLot (
id UNIQUEIDENTIFIER NOT NULL,
name NVARCHAR(50) NOT NULL,
address NVARCHAR(250) NOT NULL, -- bad way to model
CONSTRAINT FK_ParkingLot_Node
FOREIGN KEY (id) REFERENCES Node(id)
);
CREATE TABLE Food (
id UNIQUEIDENTIFIER NOT NULL,
name NVARCHAR(50) NOT NULL,
calories INT NOT NULL, -- hopefully only needs an int ;)
CONSTRAINT FK_Food_Node
FOREIGN KEY (id) REFERENCES Node(id)
);
所以現在你可以模擬任何兩個實體之間的關係,並找一找使用連接。
例如,如果你想找到哪些食物屬於哪個人,你可以說:
SELECT p.name AS person, f.name AS food
FROM Person AS p
INNER JOIN Relationships AS r
ON r.parent = p.id
INNER JOIN Food AS f
ON f.id = r.child
當然,如果你再想要找到的東西在層次更深一點,你需要專門查詢每個級別。但是,因爲你的實體(假定)是真實的東西,而不僅僅是層次結構中的層次,所以應該沒問題:)。
relationship_type =「Parking_lot」,「Car」,「Person」 – 2010-09-15 21:21:01