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

相关推荐
王有品1 小时前
Spring MVC 多个拦截器的执行顺序
数据库·spring·mvc
极小狐1 小时前
如何使用极狐GitLab 的外部状态检查功能?
数据库·ci/cd·gitlab·devops·mcp
Leo.yuan2 小时前
数据仓库建设全解析!
大数据·数据库·数据仓库·数据分析·spark
闪电麦坤952 小时前
SQL:子查询(subqueries)
数据库·sql
活跃的煤矿打工人2 小时前
【星海出品】分布式存储数据库etcd
数据库·分布式·etcd
文牧之2 小时前
PostgreSQL的扩展 pgcrypto
运维·数据库·postgresql
老友@3 小时前
小集合 VS 大集合:MySQL 去重计数性能优化
数据库·mysql·性能优化
声声codeGrandMaster4 小时前
django之优化分页功能(利用参数共存及封装来实现)
数据库·后端·python·django
麦麦大数据5 小时前
vue+neo4j+flask 音乐知识图谱推荐系统
vue.js·mysql·flask·知识图谱·neo4j·推荐算法·音乐推荐
熏鱼的小迷弟Liu5 小时前
【Redis】Redis Zset实现原理:跳表+哈希表的精妙设计
数据库·redis·散列表