简体   繁体   English

外键引用相同表

[英]Foreign Key Referencing Same Table

I've searched well and can't find an answer explaining the problem well. 我搜索得很好,找不到解答问题的答案。 Here is a simplified example of my issue. 这是我的问题的简化示例。 Let's say I have a table test with two fields first and second . 假设我有一个表testfirstsecond两个字段。 I make first the primary key and want second to reference first and cascade on update. first制作主键,并希望second引用first并在更新时级联。 This will allow me to make a list of rows, knowing which row comes after any given row, unless the 'head'. 这将允许我创建一个行列表,知道哪一行在任何给定行之后,除非'head'。

Creating the table works fine, however when I try to add a row it complains that the foreign key constraint with cascading update failed. 创建表工作正常,但是当我尝试添加一行时,它会抱怨带有级联更新的外键约束失败。 This makes sense, as I left second as null. 这是有道理的,因为我把second留作null。 Therefore, I thought I could insert two rows and then add the foreign key: 因此,我以为我可以插入两行然后添加外键:

  1. first: a second: b
  2. first: b second: a

This was successful. 这很成功。 I then tried updating row 1 to have a first value of c . 然后我尝试更新第1行以获得firstc However, this didn't work, stating the foreign key failed. 但是,这没有用,说外键失败了。 Why? 为什么? Shouldn't it just become the following? 它不应该只是变成以下?

  1. first: c second: b
  2. first: b second: c

My only hunch is the existence of circular updates with the update to row 1 cascading to row 2, cascading back to row 1, but this shouldn't happen! 我唯一的预感是存在循环更新,第1行的更新级联到第2行,级联回第1行,但这不应该发生! There is nothing referencing second , so the update should just cascade to row 2 and stop. 没有任何引用second ,所以更新应该级联到第2行并停止。 Please help, this is driving me crazy. 请帮忙,这让我发疯了。

Edit: As requested, here's my show create table test . 编辑:根据要求,这是我的show create table test

CREATE TABLE `test` (
 `first` varchar(32) NOT NULL,
 `second` varchar(32) NOT NULL,
PRIMARY KEY (`first`),
KEY `fk` (`second`),
CONSTRAINT `fk` FOREIGN KEY (`second`) REFERENCES `test` (`first`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1

I think problem is in the structure of columns: 我认为问题在于列的结构:

  • primary key can't be null 主键不能为空
  • and your referencing column has allowed null value, (not allowed when referenced column is not null) 并且您的引用列已允许空值,(当引用列不为null时不允许)

So make sure you have both columns with same data type, same charset, not null both. 因此,请确保两列具有相同的数据类型,相同的字符集,而不是两者都是空的。

Update : problem is that foreign key and referencing key is in the same table, I've tested with different table and it worked. 更新 :问题是外键和引用键是在同一个表中,我已经测试了不同的表,它工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM