【mysql】数据库插入默认值defalut

1. 插入的默认值default

sql 复制代码
drop table if exists test_default;
create table test_default(
 `id` int primary key
,`ts` timestamp default CURRENT_TIMESTAMP
) ENGINE=INNODB DEFAULT CHARSET=utf8;

truncate test_default;
insert into test_default(id,ts) values(1,default);
insert into test_default(id) values(2);
insert into test_default(id,ts) values(3,null);
insert into test_default(id,ts) values(4,20200101000000);

select * from test_default order by id;

2. 更新的默认值

sql 复制代码
drop table if exists test_onupdate;
create table test_onupdate(
 `id` int primary key
,`val` varchar(20)
,`ts` timestamp on update CURRENT_TIMESTAMP
) ENGINE=INNODB DEFAULT CHARSET=utf8;

truncate test_onupdate;
insert into test_onupdate(id,val,ts) values(1,'test',default);
insert into test_onupdate(id,val) values(2,'test');
insert into test_onupdate(id,val,ts) values(3,'test',null);
insert into test_onupdate(id,val,ts) values(4,'test',20200101000000);
insert into test_onupdate(id,val,ts) values(5,'test',20200101000000);
update test_onupdate set val='new test' where id=5;

select * from test_onupdate order by id;

3. 插入和更新的默认值

sql 复制代码
drop table if exists test_default_onupdate;
create table test_default_onupdate(
 `id` int primary key
,`val` varchar(20)
,`ts` timestamp default current_timestamp on update CURRENT_TIMESTAMP
) ENGINE=INNODB DEFAULT CHARSET=utf8;

4. 结论

(1)插入时候指定defualt是mysql,postgres,sqlserver,oracle都支持的。

(2)建表的时候字段指定default只在insert起作用,update不起作用。

(3)建表的时候字段指定on update只在update其作用。

相关推荐
changhong198616 分钟前
如何在 Spring Boot 中配置数据库?
数据库·spring boot·后端
执笔画情ora3 小时前
Postgresql数据库管理-pg_xact
数据库·postgresql·oracle
南棱笑笑生3 小时前
20260310在瑞芯微原厂RK3576的Android14查看系统休眠时间
服务器·网络·数据库·rockchip
JuneXcy3 小时前
第4章 Mysql数据操纵语句--单表查询
mysql
XDHCOM3 小时前
ORA-32152报错咋整啊,数据库操作遇到null number问题远程帮忙修复
服务器·数据库·oracle
专利观察员4 小时前
输配电行业创新转型实践:南宁迪**力有限公司的专利策略调整、专利检索工具采用
数据库·科技·专利·专利申请
jgyzl4 小时前
2026.3.9 Redis内存回收内存淘汰
数据库·redis·缓存
白露与泡影4 小时前
MySQL 时间类型选型避坑:timestamp 和 datetime 该怎么选?
数据库·mysql
青槿吖5 小时前
第二篇:告别XML臃肿配置!Spring注解式IOC/DI保姆级教程,从入门到真香
xml·java·开发语言·数据库·后端·sql·spring
运维 小白5 小时前
2. 部署mysql服务并监控mysql
数据库·mysql·adb