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

相关推荐
行十万里人生30 分钟前
Qt 对象树详解:从原理到运用
开发语言·数据库·qt·华为od·华为·华为云·harmonyos
松岛的枫叶38 分钟前
【缓冲区】数据库备份的衍生问题,缓冲区在哪里?JVMor操作系统?(二)
数据库
obboda1 小时前
使用haproxy实现MySQL服务器负载均衡
服务器·mysql·负载均衡
鸠摩智首席音效师1 小时前
解决 ERROR 1130 (HY000): Host is not allowed to connect to this MySQL server
mysql
littlegirll1 小时前
命令行方式安装KFS同步KES到KADB
java·大数据·数据库
Y编程小白2 小时前
MySQL的存储引擎
数据库·mysql
爱老的虎油2 小时前
MySQL零基础教程10—正则表达式搜索(下)
数据库·mysql·正则表达式
️Carrie️2 小时前
6.6.3 SQL数据查询(一)
数据库·sql·select·子查询·连接查询·简单查询·聚集函数
jay丿3 小时前
Django应用的高级配置和管理
数据库·django·sqlite
ILUUSION_S3 小时前
学习路程五 向量数据库Milvus操作
数据库·python·学习·langchain·milvus