Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 使用外键约束防止父行更新_Mysql - Fatal编程技术网

Mysql 使用外键约束防止父行更新

Mysql 使用外键约束防止父行更新,mysql,Mysql,当子行正在使用索引时,是否可以使用外键约束来防止更新父行 以下是父表的架构: create table if not exists incident_options ( id int not null auto_increment primary key, idx int not null, field int not null , value varchar(50)); ALTER TABLE `incident_options` ADD unique (`idx`, field);

当子行正在使用索引时,是否可以使用外键约束来防止更新父行

以下是父表的架构:

create table if not exists incident_options (
id int  not null auto_increment primary key,
idx int not null,
field int not null , 
value varchar(50));

ALTER TABLE `incident_options` ADD unique (`idx`, field);
和子表:

create table if not exists incident_values (
optn int,
value varchar(1000));

ALTER TABLE `incident_values` ADD INDEX (`optn`);
以下是我尝试过的约束条件:

ALTER TABLE `incident_values` 
ADD FOREIGN KEY (`optn`) REFERENCES `incident_options`(`id`) 
ON DELETE NO ACTION ON UPDATE RESTRICT;



假设我有以下数据:

incident_options
 __________________________
|id | idx  | field | value |    
| 1 |  0   |   1   | foo   |
| 2 |  1   |   1   | bar   |
 --------------------------

incident_values

 ______________
| optn | value |    
| 1    |  baz  |
 --------------


我试图实现的是防止“foo”被更新,因为该行在
incident\u值中使用

更新“bar”就可以了

下面是我用来修改行的查询:

insert into incident_options (`idx`,`field`,`value`)
values ('0','1','test')
on duplicate key update
`idx` = values(`idx`),
`field` = values(`field`),
`value` = values(`value`)

目前,“foo”将更新为“test”

问题是您在错误的表上设置了约束。您已将
置于
incident\u values
表上的UPDATE RESTRICT
,但在执行插入和更新时,这一切都发生在
incident\u选项上


不幸的是,您不能在
incident\u options
表中设置此约束,因为您可能并不总是有对
incident\u值的引用,因此我认为使用约束是不可能的。正如Barmar在评论中提到的,您可能能够以某种方式实现触发器,以便在更新字段之前进行验证。

通过一些黑客手段,我确实实现了我想要的

通过在“值”发生更改时强制增加“id”,如果存在关系,则不允许更新“id”

on duplicate key update
idx = values(idx),
field = values(field),
id = if(
        values(`value`)=`value`,
        id,
        (SELECT Auto_increment FROM information_schema.tables WHERE table_name='incident_options')
        ),
values= values(value)

虽然在我的应用程序中实现此解决方案之前,我会看看是否有任何建议反对使用此解决方案

否,但我认为这是不可能的。外键约束仅确保键在两个表之间正确链接,它与表中的其他列无关。也许您可以使用触发器执行任何操作。感谢您的输入,这非常有用。你介意检查一下我自己的答案,让我知道你的想法吗?我想我会尝试设置一个触发器,我的解决方案肯定太疯狂了,它不会对未来产生负面影响line@andrew祝你好运!我不是性能大师,所以我在这里绝对没有权威的意见,但我喜欢这个想法。当您测试它时,它就起作用了?我担心的是,id列的累积速度有点太快了,如果没有关系,并且修改了值,则id将增加。我可能不得不考虑使用bigint,但是是的,它是有效的