许多表引用一个表字段

时间:2012-05-24 12:34:23

标签: mysql foreign-keys innodb

有两个表 - 帖子和评论:

create table posts
(
    id integer not null primary key auto_increment,
    body text not null
);

create table comments
(
    id integer not null primary key auto_increment,
    body text not null,
    post_id integer not null references posts(id)
);

现在我想再创建一个表 - 报告(“坏帖子”标志),我希望它能存储帖子和评论的报告。

create table reports
(
    id integer not null primary key auto_increment,
    obj_type tinyint not null, /* '1' for posts and '2' for comments */
    obj_id integer not null,
    body text not null
);

alter table reports add foreign key(obj_id) references posts(id) on delete cascade;
alter table reports add foreign key(obj_id) references comments(id) on delete cascade;

如你所见,在一个字段中有两个引用(我用obj_id区分它们),问题是 - 这样做是否可以?

如果没有什么是更好的解决方案?

提前致谢。

2 个答案:

答案 0 :(得分:1)

直觉上感觉不是正确的方法。我认为MySQL也会混淆;它将如何验证是否满足约束;它会首先尝试posts,还是comments首先......也许两者都可以?

我个人会选择创建两个链接表:

  • comments <-> reports
  • posts <-> reports

这样就可以正确消除obj_id的歧义。

答案 1 :(得分:0)

你只需要引用你的评论表,因为它已经引用了帖子表,这样一旦你得到一个报告,你就有了评论的关键和帖子的关键。

相关问题