【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 天前
APM(一):Skywalking 与 Easyearch 集成
数据库·云原生
饕餮争锋1 天前
SQL条件中WHERE 1=1 的功能
数据库·sql
玄斎1 天前
MySQL 单表操作通关指南:建库 / 建表 / 插入 / 增删改查
运维·服务器·数据库·学习·程序人生·mysql·oracle
编织幻境的妖1 天前
SQL查询连续登录用户方法详解
java·数据库·sql
编程小Y1 天前
MySQL 与 MCP 集成全解析(核心原理 + 实战步骤 + 应用场景)
数据库·mysql·adb
零度@1 天前
SQL 调优全解:从 20 秒到 200 ms 的 6 步实战笔记(附脚本)
数据库·笔记·sql
Miss_Chenzr1 天前
Springboot优卖电商系统s7zmj(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
lvbinemail1 天前
Grafana模板自动复制图表
数据库·mysql·zabbix·grafana·监控
Miss_Chenzr1 天前
Springboot旅游景区管理系统9fu3n(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·旅游
小虾米vivian1 天前
dmetl5 运行失败,提示违反协议?
数据库·达梦数据库