随笔 - 465  文章 - 0  评论 - 7  阅读 - 27万

mysql-12序列使用

mysql序列是一组整数:1,2,3....,由于一张数据表只能有一个字段自增主键,如果你想实现其他字段自动增加,就可以使用mysql序列来实现。

使用auto_increment来定义列

drop table if EXISTS test_autoincrement ;
create table `test_autoincrement`(
	`id` int UNSIGNED not null auto_increment,
	PRIMARY KEY (id),
	`name` varchar(20) not null,
	`date` date not null,
	`origin` varchar(30)
	);
insert into test_autoincrement (name,date,origin) values
	('housefly','2001-09-10','kitchen');
-- 使用last_insert_id() 可以查看当前操作的次数
select LAST_INSERT_ID();
select * from test_autoincrement;
insert into test_autoincrement values
	(null,"millipede",'2001-09-10','driverway'),
	(null,"grasshopper",'2001-09-10','front yard');
-- 即便插入多行,也只显示插入第一行时产生的值
select LAST_INSERT_ID();
select * from test_autoincrement;

重置序列

先删除列,再添加列

drop table if EXISTS test_autoincrement ;
create table `test_autoincrement`(
	`id` int UNSIGNED not null auto_increment,
	PRIMARY KEY (id),
	`name` varchar(20) not null,
	`date` date not null,
	`origin` varchar(30)
	);
insert into test_autoincrement (name,date,origin) values
	('housefly','2001-09-10','kitchen'),
	("millipede",'2001-09-10','driverway'),
	("grasshopper",'2001-09-10','front yard');
alter table test_autoincrement drop id;
select * from test_autoincrement;
alter table test_autoincrement add id int(3) UNSIGNED not null auto_increment FIRST,
	add primary key (id);
select * from test_autoincrement;

设置序列的开始值

建表时设置序列值

create table `test_autoincrement` 
	(`id` int(3) UNSIGNED not null auto_increment,
	primary key (id),
	`name` varchar(20) not null )
	engine=innodb auto_increment=100 charset=utf8;
insert into test_autoincrement values
	(null,"tom"),
	(null,"jerry");
select * from test_autoincrement;
posted on   singleSpace  阅读(488)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示