4

I have a table 'release_group' and another table 'release', like so:

release_group 
------------------------
release_group_id (PRIMARY KEY)
name
main_release_id (FOREIGN KEY)

release
------------------------
release_id (PRIMARY KEY)
release_group_id (FOREIGN KEY)
name

If i create a release row, the release_group_id is not available, simply because it hasn't been created yet. But i can't create a release_group row without the main_release_id. So it's kind of a no way situation.

EDIT: The main_release_id in release_group is to say that the release is the main from the group, the one i will use a reference.

What is the professional way of handling this case?

1. Remove the foreign key index main_release_id in table release_group and give an attribute ALLOW NULL. Create the release_group row so i can applied it's id in the release row.

2. Keep the 'main_release_id' foreign key index in table 'release_group' and assign it a temporary integer value of 0. Create the release row and update the foreign key in the release_group accordingly? Keep in mind that if this is the way to go, i could end up inadvertently having foreign keys with value 0, which i don't know if this ethic in a database?

What is the professional way of handling this case?

Thanks

4

3 回答 3

5

看到一个版本不能属于多个组,您可以通过以下方式消除复杂性:

  1. 完全放弃该main_release_id领域

  2. 在表格中添加一个release_main字段;release它将是NULL(不是主要的)或1(主要的)。

  3. 添加一个UNIQUE约束(release_group_id, release_main)以确保只能有一个主要版本。

更新

如果一个版本可以属于多个组,则需要创建一个多对多表并将两个表中的外键移入其中:

(release_group_id [FK], release_id [FK], is_main)

主键将跨越前两个字段。确保只能有一个主版本需要一个跨越第一个和最后一个字段的唯一键。

旧答案

假设main_release_id是一个可为空的字段,我建议如下:

  1. 插入release_groupmain_release_id存在null;获取最后插入的 id。

  2. 插入release条目,传递上一步的id;获取最后插入的 id。

  3. 更新release_group表条目,将 的值设置为main_release_id您从上一步获得的值。

  4. 提交事务

或者,您可以使用序列,以便在插入条目之前知道 id。请参阅手册中的示例LAST_INSERT_ID()

于 2013-08-28T02:13:51.350 回答
5

看起来您正在尝试创建多对多关系。要正确执行此操作,请从 release_group 和 release 表中删除外键。添加一个包含 release_id 外键和 release 外键的新表 (release_to_release_group)。

编辑:这里不需要循环外键。从 release_group 中删除 main_release_id foreign_key 并将 is_main_release 标志添加到发布表。

于 2013-08-28T02:17:31.063 回答
2

让表像这样相互引用不是通常的做法。通常,您会将父表 (release_group) 作为子表 (release) 中的外键引用,但不会将 release_id 作为 release_group 表中的外键。

可能会在发布表中添加一个布尔标志以指示它是主版本并取消 release_group 中的 main_release_id。

于 2013-08-28T02:14:35.197 回答