Composite key as foreign key (sql)(复合键作为外键(sql))
问题描述
这是我关注的两个表:
CREATE TABLE IF NOT EXISTS `tutorial` (
`beggingTime` time NOT NULL,
`day` varchar(8) NOT NULL,
`tutorId` int(3) NOT NULL,
`maxMembers` int(2) NOT NULL,
`minMembers` int(1) NOT NULL,
PRIMARY KEY (`beggingTime`,`day`,`tutorId`),
KEY `tutorId` (`tutorId`)
)
CREATE TABLE IF NOT EXISTS `group` (
`groupId` tinyint(3) NOT NULL AUTO_INCREMENT,
`status` varchar(20) NOT NULL,
`groupName` varchar(50) NOT NULL,
PRIMARY KEY (`groupId`)
)
我想在组"中创建一个字段,该字段将链接到教程"中的复合唯一键.所以我想我的问题是,我如何关联这些表?我是否必须为教程"中的每个主键在组"中创建外键字段?
I would like to create a field in 'group' that would link to the composite unique keys in 'tutorial'. So I guess my question is, how do I relate these tables? do I have to to create foreign keys field in 'group' for each primary key in 'tutorial'?
推荐答案
根据 mySQL 文档,您应该能够设置到组合的外键映射,这将需要您创建多个列.
Per the mySQL documentation you should be able to set up a foreign key mapping to composites, which will require you to create the multiple columns.
添加列并将其放入您的 group 表
Add the columns and put this in your group table
FOREIGN KEY (`beggingTime`,`day`,`tutorId`)
REFERENCES tutorial(`beggingTime`,`day`,`tutorId`)
正如 Steven 在下面的评论中提到的,您应该尝试重新构建它,以便教程表使用实际的主键(即使它只是一个身份代理键).这将提高性能,因为 SQL 是为这种类型的关系构建的,而不是复合关系.
As Steven has alluded to in the below comments, you SHOULD try to re-architect this so that the tutorial table uses an actual primary key (even if it is just an identity surrogate key). This will allow for greater performance as SQL was built for this type of relationship, not composite.
这篇关于复合键作为外键(sql)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:复合键作为外键(sql)
基础教程推荐
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
