![](/img/trans.png)
[英]Can two columns from one table have a foreign key to the same column in another table?
[英]foreign key from one column to two columns of different table by condition
我有樹表MySQL:
文章表包含:
id int
title varchar(255)
...
新聞表包含:
id int
title varchar(255)
...
評論表包含:
id int
content text
type tinyint(1) //this column holds 0 if this comment for news and holds 1 for article
fid int // this column holds id of article or news
如何從評論表到文章和新聞使用外鍵。 我的意思是如何在MySQL查詢中實現這一點:
if type=0 then
FOREIGN KEY (fid) REFERENCES news(id)
if type=1 then
FOREIGN KEY (fid) REFERENCES articles(id)
為了擁有適當的PK-FK關系,我建議使用一個超集表(我們稱其為posts
)。 在這種情況下,您的架構可能看起來像
CREATE TABLE posts
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
type TINYINT(1)
);
CREATE TABLE articles
(
id INT NOT NULL,
title VARCHAR (255),
article_property VARCHAR(128),
-- other article specific attributes
CONSTRAINT FOREIGN KEY (id) REFERENCES posts (id)
);
CREATE TABLE news
(
id INT NOT NULL,
title VARCHAR (255),
reporter VARCHAR(128),
-- other news specific attributes
CONSTRAINT FOREIGN KEY (id) REFERENCES posts (id)
);
CREATE TABLE comments
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
content TEXT,
CONSTRAINT FOREIGN KEY (post_id) REFERENCES posts (id)
);
要在插入新文章和新聞時填充id
,可以使用觸發器
DELIMITER $$
CREATE TRIGGER tg_article_insert
BEFORE INSERT ON articles
FOR EACH ROW
BEGIN
INSERT INTO posts (type) VALUES (1);
SET NEW.id = LAST_INSERT_ID();
END$$
CREATE TRIGGER tg_news_insert
BEFORE INSERT ON news
FOR EACH ROW
BEGIN
INSERT INTO posts (type) VALUES (0);
SET NEW.id = LAST_INSERT_ID();
END$$
DELIMITER ;
這是SQLFiddle演示。
你不能 您可以在此處閱讀有關外鍵約束的信息 ,並且您會注意到只允許一個表。
一種解決方法是為單獨的ID提供單獨的列:
id int
content text
type tinyint(1) //this column holds 0 if this comment for news and holds 1 for article
articleid int
newsid int
. . .
foreign key (articleid) references articles(id)
foreign key (newsid) references news(id)
實際上,您可以省去該type
並添加一個約束(由觸發器實現),該約束在任何給定時間只能填充一個ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.