【问题标题】:Many tables referencing to one table field多个表引用一个表字段
【发布时间】:2012-05-24 12:34:23
【问题描述】:

有两个表——posts 和 cmets:

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)
);

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

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 区分它们),问题是 - 这样做可以吗?

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

提前致谢。

【问题讨论】:

    标签: mysql foreign-keys innodb


    【解决方案1】:

    直觉上觉得这不是正确的做法。我认为 MySQL 也会感到困惑;它如何验证是否满足约束;它会先尝试posts,还是先尝试comments……也许两者兼而有之?

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

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

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

    【讨论】:

    • 其实我用的是Yii php框架,我可以从那里处理“on delete cascade”。我需要外键来使用 ORM 级别的关系。重要的是,posts 和 cmets 只是一个例子,实际上我需要 4 个表的标志。我想要一些灵活的方式,而不需要额外的 4 个表。
    • @Acute 说实话,我不知道 MySQL 是如何将这两个外键分开的 =/ 也许这是一个特殊功能?
    • 我不知道,但我不喜欢创建多个 FK,看起来不像是一个优雅的解决方案)好的,如果我决定做链接表,我会选择你的答案作为解决方案
    • dba.stackexchange.com/q/2754/8975 @DrColossos 说有很多FK没关系,还是我理解错了?
    • @Acute 他实际上并不是指外键附带的约束,只是键引用另一个表和表选择器字段的想法。另见:stackoverflow.com/a/1186979/1338292
    【解决方案2】:

    您只需要引用您的 cmets 表,因为它已经引用了 posts 表,这样,每当您收到报告时,您就拥有评论的密钥和帖子的密钥。

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多