当用户在表单中编辑值时,我尝试在NULL
列中设置deserved_slope_2
值。不幸的是,这个列是一个外键,它链接到另一个表的列的主键(自动增量索引)。
运行请求时,我得到:
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (`game_skisimulation`.`game_created_lifts`, CONSTRAINT `fk_game_created_lifts_game_created_slopes2` FOREIGN KEY (`deserved_slope_2`) REFERENCES `game_created_slopes` (`id_created_slopes`) ON DE)
UPDATE game_created_lifts SET deserved_slope_2 = '0' WHERE id_created_lifts = '200' LIMIT 1
我读过这是因为在引用的表中不存在NULL ID。不幸的是,我似乎无法在此列中设置NULL:
主键列不能包含NULL值。
我该如何解决这个问题?
我想在deserved_slope_2
列中设置NULL(重置它)。
- 表game_created_lifts
CREATE TABLE `game_created_lifts` (
`id_created_lifts` int(11) NOT NULL,
`id_player` int(11) NOT NULL,
`deserved_slope_1` int(11) DEFAULT NULL,
`deserved_slope_2` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- RELATIONS FOR TABLE `game_created_lifts`:
-- `deserved_slope_1`
-- `game_created_slopes` -> `id_created_slopes`
-- `deserved_slope_2`
-- `game_created_slopes` -> `id_created_slopes`
- 表game_created_slopes
CREATE TABLE `game_created_slopes` (
`id_created_slopes` int(11) NOT NULL,
`id_player` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
答案 0 :(得分:0)
在具有依赖于唯一且非空列的外键约束的列中将值设置为null应该非常简单
UPDATE game_created_lifts SET deserved_slope_2 = NULL WHERE id_created_lifts = '200' LIMIT 1;
转到SQL Fiddle在线查看。
测试数据:
create table a (a int primary key);
create table b (a int references a(a));
insert into a(a) values (1);
insert into b(a) values (1);
update b set a = null;
查询:
select * from b
结果:
(null)