MySQL 困境:跨表复合唯一键
我正在尝试为我从多个来源收集的一些统计数据实现“扩展”表结构。
我的“父”表看起来像这样:
`test_parent` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`actions` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`)
)
我的第一个“子”表看起来像这样(最终我将为每个源都有一个子表):
`test_child` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`test_parent_id` int(11) unsigned NOT NULL,
`external_id` int(11) NOT NULL,
`external_actions` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `test_parent_id` (`test_parent_id`)
)
CONSTRAINT `test_child_ibfk_1` FOREIGN KEY (`test_parent_id`) REFERENCES `test_parent` (`id`)
所有这些都将在我的实现中正常工作(我将使用 Java/Hibernate);但是,对于第一个子表,我将需要 external_id 和日期的复合唯一键。我知道我不能在表之间拥有复合唯一键。我不想用一张表来存储所有统计数据,因为我收集的实际分析数据可能因来源而异。我会更愿意摆脱“父”表。
我还有其他方法可以看待这个问题吗?如果可能的话,我希望避免使用触发器来强制唯一性。
I am attempting to implement an "extension" table structure for some stats that I am gathering from multiple sources.
My "parent" table looks something like this:
`test_parent` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`actions` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`)
)
My first "child" table looks somethinglike this (eventually I will have a child table for each source):
`test_child` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`test_parent_id` int(11) unsigned NOT NULL,
`external_id` int(11) NOT NULL,
`external_actions` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `test_parent_id` (`test_parent_id`)
)
CONSTRAINT `test_child_ibfk_1` FOREIGN KEY (`test_parent_id`) REFERENCES `test_parent` (`id`)
All this will work fine in my implementation (I will be using Java/Hibernate); however, for the first child table I will need a composite unique key for external_id and date. I know that I cannot have a composite unique key across tables. I would rather not have one table to store all of the stats because the actual analytics I am collecting can vary greatly by source. I would be more open to getting rid of the "parent" table.
Is there some other way I can look at this problem? I am hoping to avoid using triggers to enforce uniqueness, if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想使用
external_id
对其建立唯一约束,则需要子表中的date
。您还可以将date
保留在父表中,并通过外键引用它。这将允许您将来通过其他子表以不同的方式支持date
。You need the
date
in the child table if you want to establish a unique constraint on it withexternal_id
. You can also havedate
live in the parent table, and reference it via the foreign key. That will allow you to supportdate
differently by other child tables in the future.将
date
字段移至子表并声明一个唯一键:Move the
date
field to the child table and declare a unique key: