对已有的表字段修改设置默认值,会影响原来数据中为null的字段数据吗?

1.新建表 t_user
CREATE TABLE `t_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `male` varchar(100) NOT NULL,
  `height` int(11) NOT NULL,
  `if_delete` tinyint(1),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1425357 DEFAULT CHARSET=utf8;

 2.插入数据

INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (1, '张三', 19, '1', 180, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (2, '张三', 19, '1', 180, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (3, '张三', 19, '1', 180, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (4, '张三', 19, '1', 180, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (5, '张三', 19, '1', 180, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (6, '张三', 19, '1', 180, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (7, '张三', 19, '1', 180, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (8, '张三', 19, '1', 180, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (9, '张三', 19, '1', 180, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (10, 'liuss', 111, '11', 1601, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (11, '1', 1, '1', 1, NULL);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (13, 'liu', 11, '1', 160, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (14, 'liu', 11, '1', 160, 0);
INSERT INTO `test`.`t_user`(`id`, `name`, `age`, `male`, `height`, `if_delete`) VALUES (15, 'liu', 11, '1', 160, 1);

3.可以看到id=11的数据 if_delete字段是null
修改表中 if_delete字段的默认值为0:

ALTER TABLE t_user  MODIFY COLUMN if_delete tinyint(1) DEFAULT '0' COMMENT '是否删除 0-否 1-是';

查看表的DDL 

 设置成功!

 

查看t_user表的数据:会发现id=11的if_delete字段依旧为null(由此可得 修改字段的默认值为已有数据没有影响)

 

测试新增一条数据,此字段的默认值是否有:

insert into t_user(id,name,age,male,height) VALUES(16,'test',11,'1',160);

默认值数据生效

 结论:对于已经存在的字段,新增默认值,不会影响原有数据此字段的null值,对于已经设置了了默认值的新增数据,默认值会应用上。

 

那么如何对已存在的数据让让进行默认值生效?

replace into t_user(id,name,age,male,height) values(10,'liuss',111,'11',1601);

 新增字段,且设置默认值,新增列数据会受默认值影响。

 

posted @ 2023-05-22 16:53  ldlei  阅读(340)  评论(0编辑  收藏  举报