博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在MySQL中两个实体怎么匹配_如何设计数据库约束,以便两个实体只有其中两个字段值匹配才可以有多对多关系?...
阅读量:5743 次
发布时间:2019-06-18

本文共 1876 字,大约阅读时间需要 6 分钟。

bd96500e110b49cbb3cd949968f18be7.png

I have a database with four tables as follows:

Addressbook

--------------------

id

more fields

Contact

---------------------

id

addressbook id

more fields

Group

---------------------

id

addressbook id

more fields

Group to Contact

---------------------

Composite key

Group id

Contact id

My relationships are one to many for addressbook > contact, one to many for addressbook > group and many to many between contact and groups.

So in summary, I have an addressbook. Contacts and groups can be stored within it and they cannot be stored in more than one addressbook. Furthermore as many contacts that are needed can be added to as many groups as are needed.

My question now poses as follows. I wish to add the constraint that a contact can only be a member of a group if both of them have the same addressbook id.

As I am not a database person this is boggling my brain. Does this mean I have designed my table structure wrong? Or does this mean that I have to add a check somewhere before inserting into the group to contact table? This seems wrong to me because I would want it to be impossible for SQL queries to link contacts to groups if they do not have the same id.

解决方案

You should be able to accomplish this by adding a addressbook_id column to your Group to Contact bridge table, then using a compound foreign key to both the Contacts and Groups tables.

In PostgreSQL (but easily adaptable to any DB, or at least any DB that supports compound FKs):

CREATE TABLE group_to_contact (

contact_id INT,

group_id INT,

addressbook_id INT,

CONSTRAINT contact_fk FOREIGN KEY (contact_id,addressbook_id)

REFERENCES contacts(id,addressbook_id),

CONSTRAINT groups_fk FOREIGN KEY (group_id,addressbook_id)

REFERENCES groups(id,addressbook_id)

)

By using the same addressbook_id column in both constraints, you are of course enforcing that they are the same in both referenced tables.

转载地址:http://hynzx.baihongyu.com/

你可能感兴趣的文章
ZJU PAT 1023
查看>>
WMI远程访问问题解决方法
查看>>
从零开始学习IOS,(UILabel控件)详细使用和特殊效果
查看>>
Android开发历程_15(AppWidget的使用)
查看>>
阿花宝宝 Java 笔记 之 初识java
查看>>
7、设计模式-创建型模式-建造者模式
查看>>
Cesium官方教程11--建模人员必读
查看>>
我国古代的勾股定理
查看>>
Linux下的C编程实战
查看>>
[32期] html中部分代码与英语单词关系
查看>>
PHP安装环境,服务器不支持curl_exec的解决办法
查看>>
jQuery|元素遍历
查看>>
RedHat 6 安装配置Apache 2.2
查看>>
Openstack 安装部署指南翻译系列 之 Manila服务安装(Share Storage)
查看>>
underscore.js学习笔记
查看>>
windows下常用命令
查看>>
1.5编程基础之循环控制_29:数字反转
查看>>
组策略 之 设备安装设置
查看>>
人工智能还能干这些?这8种AI应用你可能意想不到
查看>>
实现Hyper-V 虚拟机在不同架构的处理器间迁移
查看>>