【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其作用。

相关推荐
川石课堂软件测试36 分钟前
MySQL数据库之DBA命令
数据库·网络协议·mysql·http·单元测试·prometheus·dba
ybb_ymm2 小时前
mysql8在linux下的默认规则修改
linux·运维·数据库·mysql
倔强的石头_3 小时前
Navicat Premium 与金仓数据库融合实践:高效管理国产数据库新方案
数据库
程序新视界4 小时前
为什么要尽量将MySQL表字段要设置为NOT NULL?
数据库·mysql·dba
怪兽20144 小时前
SQL优化手段有哪些
java·数据库·面试
lypzcgf4 小时前
FastbuildAI后端数据库模块注册分析
数据库·ai应用·ai创业·智能体平台·ai应用平台·agent平台·fastbuildai
xyy20255 小时前
Spring事务的传播方式
java·数据库·spring
非凡的世界5 小时前
Thinkphp8 Redis队列与消息队列topthink/think-queue 原创
数据库·redis·bootstrap·thinkphp
yookay zhang5 小时前
DM线程的管理知识学习
数据库