可以有2个实体有2个关系

时间:2012-01-25 10:31:02

标签: mysql database

在数据库设计中,2个实体之间可以有2个关系吗?例如,有2个实体捐赠者和管理者......有2个关系 1.管理员访问捐赠者的详细信息 2.管理员可以联系捐赠者,反之亦然 我们可以加入2个关系吗?

1 个答案:

答案 0 :(得分:1)

当然,尽管在数据库中对“访问”和“联系人”关系进行建模有多大意义取决于您的应用程序。我将继续你的例子,并假设这些关系是n到n。以下是SQL的外观(警告,语法未测试):

CREATE TABLE admin (
    id int unsigned AUTO_INCREMENT PRIMARY KEY,
    name text NOT NULL
);

CREATE TABLE donor (
    id int unsigned AUTO_INCREMENT PRIMARY KEY,
    name text NOT NULL
);

CREATE TABLE admin_donor_access_details (
    id_admin int unsigned NOT NULL,
    id_donor int unsigned NOT NULL,
    PRIMARY KEY (id_admin, id_donor),
    CONSTRAINT FOREIGN KEY(id_admin) REFERENCES admin(id) ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT FOREIGN KEY(id_donor) REFERENCES donor(id) ON DELETE CASCADE ON UPDATE CASCADE
);

CREATE TABLE admin_donor_contact (
    id_admin int unsigned NOT NULL,
    id_donor int unsigned NOT NULL,
    PRIMARY KEY (id_admin, id_donor),
    CONSTRAINT FOREIGN KEY(id_admin) REFERENCES admin(id) ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT FOREIGN KEY(id_donor) REFERENCES donor(id) ON DELETE CASCADE ON UPDATE CASCADE
);

这两个关系也可以在一个带有布尔标志的连接表中表示,如下所示:

CREATE TABLE admin_donor (
    id_admin int unsigned NOT NULL,
    id_donor int unsigned NOT NULL,
    detail_access tinyint(1) NOT NULL,
    contact tinyint(1) NOT NULL,
    PRIMARY KEY (id_admin, id_donor),
    CONSTRAINT FOREIGN KEY(id_admin) REFERENCES admin(id) ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT FOREIGN KEY(id_donor) REFERENCES donor(id) ON DELETE CASCADE ON UPDATE CASCADE
);

这将为您的代码增加一些额外的工作量,因为您需要确定在添加关系时是插入还是更新行,以及在删除关系时是删除还是更新行,但我认为这仍然是可用的替代方案。