mysql外键设置条件,MySQL - 有条件的外键限制

I have following 'comments' table in my app:

comments

--------

id INT

foreign_id INT

model TEXT

comment_text TEXT

...

the idea of this table is to store comments for various parts of my app - it can store comments for blog post i.e:

1|34|blogpost|lorem ipsum...

user picture:

2|12|picture|lorem ipsum...

and so on.

now, is there a way to force FOREIGN KEY constraint on such data?

i.e. something like this in comments table:

FOREIGN KEY (`foreign_id`) REFERENCES blogposts (`id`)

//but only when model='blogpost'

解决方案

You're attempting to do a design that is called Polymorphic Associations. That is, the foreign key may reference rows in any of several related tables.

But a foreign key constraint must reference exactly one table. You can't declare a foreign key that references different tables depending on the value in another column of your Comments table. This would violate several rules of relational database design.

A better solution is to make a sort of "supertable" that is referenced by the comments.

CREATE TABLE Commentable (

id SERIAL PRIMARY KEY

);

CREATE TABLE Comments (

comment_id SERIAL PRIMARY KEY,

foreign_id INT NOT NULL,

...

FOREIGN KEY (foreign_id) REFERENCES Commentable(id)

);

Each of your content types would be considered a subtype of this supertable. This is analogous to the object-oriented concept of an interface.

CREATE TABLE BlogPosts (

blogpost_id INT PRIMARY KEY, -- notice this is not auto-generated

...

FOREIGN KEY (blogpost_id) REFERENCES Commentable(id)

);

CREATE TABLE UserPictures (

userpicture_id INT PRIMARY KEY, -- notice this is not auto-generated

...

FOREIGN KEY (userpicture_id) REFERENCES Commentable(id)

);

Before you can insert a row into BlogPosts or UserPictures, you must insert a new row to Commentable to generate a new pseudokey id. Then you can use that generated id as you insert the content to the respective subtype table.

Once you do all that, you can rely on referential integrity constraints.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值