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

相关推荐
爱写bug的野原新之助3 分钟前
数据库及navicat工具
数据库·网络爬虫·工具
数据知道6 分钟前
一文掌握 MongoDB 存储引擎 WiredTiger 的原理
数据库·mongodb·数据库架构
Full Stack Developme10 分钟前
Mycat 2 实现 MySQL 读写分离,并且实现 主从同步
android·数据库·mysql
我是人✓14 分钟前
Spring IOC入门
java·数据库·spring
Hello.Reader15 分钟前
PyFlink DataStream 程序骨架、常用 Source/Sink、状态(State)、与 Table/SQL 互转一篇搞定
数据库·sql·linq
三不原则22 分钟前
故障案例:模型推理响应慢,排查 Redis 缓存集群问题
数据库·redis·缓存
alonewolf_9927 分钟前
MySQL Explain详解与索引优化实战
数据库·mysql·adb
それども32 分钟前
MySQL 查询索引最左前缀原则,如果是(a,b)的联合索引,WHERE b = ? AND a = ?会走索引吗
数据库·mysql
それども33 分钟前
MySQL EXPLAIN Impossible WHERE noticed after reading const tables
数据库·mysql
a程序小傲36 分钟前
得物Java面试被问:边缘计算的数据同步和计算卸载
java·开发语言·数据库·后端·面试·golang·边缘计算