我回答了一個非常類似的問題: In a StackOverflow clone, what relationship should a Comments table have to Questions and Answers?
在你的情況,我建議建立一個單一的表Commentables:
CREATE TABLE Commentables (
item_id INT AUTO_INCREMENT PRIMARY KEY
item_type CHAR(1) NOT NULL,
UNIQUE KEY (item_id, item_type)
);
然後書籍,圖片,文件中的每一個與Commentables的關係都是1:1。
CREATE TABLE Books (
book_id INT PRIMARY KEY, -- but not auto-increment
item_type CHAR(1) NOT NULL DEFAULT 'B',
FOREIGN KEY (book_id, item_type) REFERENCES Commentables(item_id, item_type)
);
對圖片和文件做同樣的事情。對於圖書,item_type應始終爲'B',對於圖片始終爲'P',對於文件始終爲'F'。因此,您無法將圖書和圖片引用到Commentables中的同一行。
然後你的意見可以參考一個表,Commentables:
CREATE TABLE Comments (
comment_id INT AUTO_INCREMENT PRIMARY KEY,
item_id INT NOT NULL,
FOREIGN KEY (item_id) REFERENCES Commentables (item_id)
);
請訪問http://計算器。com/questions/987654/in-a-stackoverflow-clone-what-relationship-should-a-comments-table-have-to-ques/987709#987709 –
這意味着創建一個與item_id和dataItem_id的一對一關係例如? 創建評論表comment_id,item_id –
我會在下面寫一個答案。 –