SQL 索引删除时出现问题
我有一些表:
- 表 ASK 与
idask
- 表 PREFERENCES 与
idpref
、fk_idask
、fk_idstruct
- 表 STRUCTURE 与
idstruct
具有 id
和 fk_id
之间的所有约束以及表 PREFERENCES 上的唯一索引 (fk_idask
, fk_id结构
)。
问题是当我在首选项中有两行时。
`IDPREF` `FK_IDASK` `FK_IDSTRUCTURE`
1 1 1
2 1 2
如果我想反转(切换?)首选项之间的两个结构
`IDPREF` `FK_IDASK` `FK_IDSTRUCTURE`
1 1 **2**
2 1 **1**
FK_IDASK
和 FK_IDSTRUCTURE
之间的唯一索引会破裂,因为第一次更新会导致两个首选项具有相同结构的相同询问。
为了防止这种情况,我创建了一个函数deleteAndResave,这暂时解决了问题。
但现在 ASSIGNATION 表带有 idassignation 和 fk_idpref。
现在,如果我删除由分配链接的首选项,约束就会中断。
我已经找到了解决方法,但是很难看。 这个问题有一些明智的解决方案吗?
感谢你的回答!
附: 对不起,我的英语不好 :(
I have some table:
- table ASK with
idask
- table PREFERENCES with
idpref
,fk_idask
,fk_idstructure
- table STRUCTURE with
idstructure
With all the constraint between the id
and the fk_id
and a unique index on the table PREFERENCES (fk_idask
, fk_idstructure
).
The problem is when I have two row in PREFERENCES.
`IDPREF` `FK_IDASK` `FK_IDSTRUCTURE`
1 1 1
2 1 2
If I want to invert(switch?) the two structure between the preferences
`IDPREF` `FK_IDASK` `FK_IDSTRUCTURE`
1 1 **2**
2 1 **1**
The unique index between FK_IDASK
and FK_IDSTRUCTURE
break up, because with the first update result in two preferences for the same ask with the same structure.
For prevent this, I make a function deleteAndResave and this solve the problem for the moment.
But now the arrive the ASSIGNATION table with idassignation
and fk_idpref
.
Now if I delete a Preference linked by an ASSIGNATION the constraint break.
I already find a workaround, but is ugly. There is some sane solution for this problem?
Thanks for the answer!
ps. Sorry for my bad english :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以试试这个:
现在,因为它是一次性运行的,所以“ACID”中的“C”(一致性)意味着外键和唯一性在“期间”处理,但在之前和之后都可以。
您可以使用 CASE 语句来处理更复杂的内容
You could try this:
Now, because it runs in one go, the "C" (Consistency) in "ACID" means that foreign keys and uniqueness are handled "during" but will be OK before and after.
You can pimp the statement with CASE statements for more complex stuff
是的,颠倒了表索引之间的两个结构并分解了!
不管怎样,我猜你的外键指向了错误的方向。 看起来外键正在分配,并指向首选项。
外键应该位于偏好和引用分配上。
另一种选择是考虑外键上的 ON DELETE CASCADE 选项。 这意味着当您删除引用表中的行时,数据库引擎会自动删除外键表中的相关行。
另一个常用的选项是保留行,但将它们标记为非活动状态。 这可以通过添加“活动位”列来完成。 查询时,您可以过滤掉标记为非活动的行。
Yah, inverted two structures between table index and break up!
Anyway, I'm guessing your foreign key is pointing the wrong way. It looks like the foreign key is on assignation, and pointing to preferences.
The foreign key should be on preferences, and REFERENCE assignation.
Another option is to consider an ON DELETE CASCADE option on the foreign key. This means that when you delete rows in the referenced table, the database engine automatically deletes the relevant rows in the foreign key table.
Another often used option is to keep the rows, but mark them as inactive. This can be done by adding an "active bit" column. When querying you filter out the rows marked as inactive.