第11章:生成和使用序列
11.0 引言

11.1 创建一个序列列并生成序列值

CREATE TABLE insect (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL);
字段说明
‌id‌:主键,自动递增。
‌name‌:字符串类型,存储昆虫的名称。
‌date‌:日期类型,存储采集日期。
‌origin‌:字符串类型,存储采集地点。mysql> select * from insect;
+----+-------------------+------------+------------------+
| id | name              | date       | origin           |
+----+-------------------+------------+------------------+
|  1 | housefly          | 2014-09-10 | kitchen          |
|  2 | millipede         | 2014-09-10 | driveway         |
|  3 | grasshopper       | 2014-09-10 | front yard       |
|  4 | stink bug         | 2014-09-10 | front yard       |
|  5 | cabbage butterfly | 2014-09-10 | garden           |
|  6 | ant               | 2014-09-10 | back yard        |
|  7 | ant               | 2014-09-10 | back yard        |
|  8 | termite           | 2014-09-10 | kitchen woodwork |
+----+-------------------+------------+------------------+
8 rows in set (0.01 sec)mysql> describe insect;
+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int unsigned | NO   | PRI | NULL    | auto_increment |
| name   | varchar(30)  | NO   |     | NULL    |                |
| date   | date         | NO   |     | NULL    |                |
| origin | varchar(30)  | NO   |     | NULL    |                |
+--------+--------------+------+-----+---------+----------------+
4 rows in set (0.04 sec)id 字段是自增主键(auto_increment),这意味着 MySQL 会自动为新记录分配唯一的 ID 值。
更新现有记录:如果需要修改 ID 为 3 的记录,使用UPDATE语句:
sql
UPDATE insect 
SET name = 'cricket', date = '2014-09-10', origin = 'basement' 
WHERE id = 3;
忽略重复:如果允许重复数据,可以使用INSERT IGNORE(但会静默失败):
sql
INSERT IGNORE INTO insect (id, name, date, origin) 
VALUES (3, 'cricket', '2014-09-10', 'basement');替换数据:使用REPLACE INTO覆盖现有记录:
sql
REPLACE INTO insect (id, name, date, origin) 
VALUES (3, 'cricket', '2014-09-10', 'basement');

11.2 为序列列选择数据类型

11.3 序列生成的行删除的效果

mysql> select * from insect order by id;
+----+-------------------+------------+------------------+
| id | name              | date       | origin           |
+----+-------------------+------------+------------------+
|  1 | housefly          | 2014-09-10 | kitchen          |
|  2 | millipede         | 2014-09-10 | driveway         |
|  3 | grasshopper       | 2014-09-10 | front yard       |
|  4 | stink bug         | 2014-09-10 | front yard       |
|  5 | cabbage butterfly | 2014-09-10 | garden           |
|  6 | ant               | 2014-09-10 | back yard        |
|  7 | ant               | 2014-09-10 | back yard        |
|  8 | termite           | 2014-09-10 | kitchen woodwork |
+----+-------------------+------------+------------------+
8 rows in set (0.00 sec)mysql> delete from insect where id in(2, 6);
Query OK, 2 rows affected (0.01 sec)mysql> select * from insect order by id;
+----+-------------------+------------+------------------+
| id | name              | date       | origin           |
+----+-------------------+------------+------------------+
|  1 | housefly          | 2014-09-10 | kitchen          |
|  3 | grasshopper       | 2014-09-10 | front yard       |
|  4 | stink bug         | 2014-09-10 | front yard       |
|  5 | cabbage butterfly | 2014-09-10 | garden           |
|  7 | ant               | 2014-09-10 | back yard        |
|  8 | termite           | 2014-09-10 | kitchen woodwork |
+----+-------------------+------------+------------------+
6 rows in set (0.00 sec)mysql> delete from insect where id in(8);
Query OK, 1 row affected (0.01 sec)mysql> select * from insect order by id;
+----+-------------------+------------+------------+
| id | name              | date       | origin     |
+----+-------------------+------------+------------+
|  1 | housefly          | 2014-09-10 | kitchen    |
|  3 | grasshopper       | 2014-09-10 | front yard |
|  4 | stink bug         | 2014-09-10 | front yard |
|  5 | cabbage butterfly | 2014-09-10 | garden     |
|  7 | ant               | 2014-09-10 | back yard  |
+----+-------------------+------------+------------+
5 rows in set (0.00 sec)mysql> select engine from information_schema.tables-> where table_schema='cookbook' and table_name='insect';
+--------+
| ENGINE |
+--------+
| InnoDB |
+--------+
1 row in set (0.01 sec)mysql> alter table insect engine = MyISAM;
Query OK, 5 rows affected (0.12 sec)
Records: 5  Duplicates: 0  Warnings: 0mysql> select engine from information_schema.tables-> where table_schema='cookbook' and table_name='insect';
+--------+
| ENGINE |
+--------+
| MyISAM |
+--------+
1 row in set (0.00 sec)  

2025年6月29日星期日
11.4 查询序列值

mysql> select * from  insect order by id;
+----+-------------------+------------+------------+
| id | name              | date       | origin     |
+----+-------------------+------------+------------+
|  1 | housefly          | 2014-09-10 | kitchen    |
|  3 | grasshopper       | 2014-09-10 | front yard |
|  4 | stink bug         | 2014-09-10 | front yard |
|  5 | cabbage butterfly | 2014-09-10 | garden     |
|  7 | ant               | 2014-09-10 | back yard  |
+----+-------------------+------------+------------+
5 rows in set (0.01 sec)mysql> delete from insect where id in (2, 6, 8);
Query OK, 0 rows affected (0.00 sec)mysql> alter table tbl_name engine = MyISAM;
Query OK, 6 rows affected (0.36 sec)
Records: 6  Duplicates: 0  Warnings: 0mysql> select engine from information_schema.tables-> where table_schema = 'cookbook' and table_name = 'insect';
+--------+
| ENGINE |
+--------+
| MyISAM |
+--------+
1 row in set (0.00 sec)想清除一张表的所有信息
Truncate table
Truncate table tbl_namemysql> select max(id) from insect;
+---------+
| max(id) |
+---------+
|       7 |
+---------+
1 row in set (0.00 sec)mysql> insert into insect (name, date, origin)-> values('cricket', '2006-09-11', 'basement');
Query OK, 1 row affected (0.01 sec)mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                9 |
+------------------+
1 row in set (0.00 sec)mysql> insert into insect (name, date, origin)-> values('month', '2006-09-14', 'windowsill');
Query OK, 1 row affected (0.01 sec)mysql> select * from insect where id = last_insert_id();
+----+-------+------------+------------+
| id | name  | date       | origin     |
+----+-------+------------+------------+
| 10 | month | 2006-09-14 | windowsill |
+----+-------+------------+------------+
1 row in set (0.00 sec)
Notepad++  insert.pl  use strict;
use warnings;
use DBI;# Connect to your database
my $dbh = DBI->connect("DBI:mysql:database=cookbook;host=localhost", "cbuser", "cbpass") or die "Could not connect to database: $DBI::errstr";# Execute your insert
$dbh->do("insert into insect (name, date, origin) values('moth', '2006-09-14','windowsill')");# Get the insert ID
my $seq = $dbh->{mysql_insertid};  # or $dbh->last_insert_id(...) depending on your driverprint "Inserted record with ID: $seq\n";# Disconnect
$dbh->disconnect;C:\Users\lenovo>perl insert.pl
Inserted record with ID: 11
C:\Users\lenovo>mysql -u cbuser -p
Enter password: ******
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 185
Server version: 8.0.40 MySQL Community Server - GPLCopyright (c) 2000, 2024, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> use cookbook;
Database changed
mysql> select * from insect;
+----+-------------------+------------+------------+
| id | name              | date       | origin     |
+----+-------------------+------------+------------+
|  1 | housefly          | 2014-09-10 | kitchen    |
|  3 | grasshopper       | 2014-09-10 | front yard |
|  4 | stink bug         | 2014-09-10 | front yard |
|  5 | cabbage butterfly | 2014-09-10 | garden     |
|  7 | ant               | 2014-09-10 | back yard  |
|  9 | cricket           | 2006-09-11 | basement   |
| 10 | month             | 2006-09-14 | windowsill |
| 11 | moth              | 2006-09-14 | windowsill |
+----+-------------------+------------+------------+
8 rows in set (0.00 sec)
# Execute your insert  第一种方法
#$dbh->do("insert into insect (name, date, origin) values('moth', '2006-09-14','windowsill')");
替换成以下方法#第二种方法
my $sth = $dbh->prepare("insert into insect (name, date, origin) values('moth2', '2006-09-14','windowsill')");
$sth->execute();
C:\Users\lenovo>perl insert.pl
Inserted record with ID: 12
import mysql.connector
from mysql.connector import Error
from mysql.connector import constantstry:conn = mysql.connector.connect(host='localhost',database='cookbook',user='cbuser',password='cbpass',client_flags=[constants.ClientFlag.FOUND_ROWS])if conn.is_connected():print('已成功连接到数据库')stmt = "insert into insect (name, date, origin) values('moth3', '2006-09-14', 'windowsill')"print("执行查询:", stmt)cursor = conn.cursor()cursor.execute(stmt)print(f"查询返回 {cursor.rowcount} 条记录")
except Error as e:
print(f'数据库操作错误: {e}')已成功连接到数据库
执行查询: insert into insect (name, date, origin) values('moth3', '2006-09-14', 'windowsill')
查询返回 1 条记录import mysql.connector
from mysql.connector import Error
from mysql.connector import constantstry:conn = mysql.connector.connect(host='localhost',database='cookbook',user='cbuser',password='cbpass',client_flags=[constants.ClientFlag.FOUND_ROWS])if conn.is_connected():print('已成功连接到数据库')# 创建游标cursor = conn.cursor()# 执行插入操作(使用您要求的格式)cursor.execute("""insert into insect (name, date, origin)values('moth4', '2006-09-14', 'windowsill')""")# 获取最后插入的IDlast_id = cursor.lastrowidprint(f"最后插入的记录ID: {last_id}")# 提交事务conn.commit()print(f"影响的行数: {cursor.rowcount}")except Error as e:print(f'数据库操作错误: {e}')# 发生错误时回滚if 'conn' in locals():conn.rollback()finally:# 关闭游标和连接if 'cursor' in locals():cursor.close()if 'conn' in locals() and conn.is_connected():conn.close()print('数据库连接已关闭')

已成功连接到数据库
最后插入的记录ID: 14
影响的行数: 1
数据库连接已关闭

mysql> select * from insect;
+----+-------------------+------------+------------+
| id | name              | date       | origin     |
+----+-------------------+------------+------------+
|  1 | housefly          | 2014-09-10 | kitchen    |
|  3 | grasshopper       | 2014-09-10 | front yard |
|  4 | stink bug         | 2014-09-10 | front yard |
|  5 | cabbage butterfly | 2014-09-10 | garden     |
|  7 | ant               | 2014-09-10 | back yard  |
|  9 | cricket           | 2006-09-11 | basement   |
| 10 | month             | 2006-09-14 | windowsill |
| 11 | moth              | 2006-09-14 | windowsill |
| 12 | moth2             | 2006-09-14 | windowsill |
| 13 | moth3             | 2006-09-14 | windowsill |
| 14 | moth4             | 2006-09-14 | windowsill |
+----+-------------------+------------+------------+
11 rows in set (0.00 sec)```sql
在这里插入代码片

11.5 对一个已有的序列进行重新计数

mysql> alter table insect drop id;
Query OK, 11 rows affected (0.07 sec)
Records: 11  Duplicates: 0  Warnings: 0mysql> alter table insect-> add id int unsigned not null auto_increment first,-> add primary key(id);
Query OK, 11 rows affected (0.04 sec)
Records: 11  Duplicates: 0  Warnings: 0mysql> select * from insect order by id;
+----+-------------------+------------+------------+
| id | name              | date       | origin     |
+----+-------------------+------------+------------+
|  1 | housefly          | 2014-09-10 | kitchen    |
|  2 | grasshopper       | 2014-09-10 | front yard |
|  3 | stink bug         | 2014-09-10 | front yard |
|  4 | cabbage butterfly | 2014-09-10 | garden     |
|  5 | ant               | 2014-09-10 | back yard  |
|  6 | cricket           | 2006-09-11 | basement   |
|  7 | month             | 2006-09-14 | windowsill |
|  8 | moth              | 2006-09-14 | windowsill |
|  9 | moth2             | 2006-09-14 | windowsill |
| 10 | moth3             | 2006-09-14 | windowsill |
| 11 | moth4             | 2006-09-14 | windowsill |
+----+-------------------+------------+------------+
11 rows in set (0.00 sec)Mysql->alter table insert
Drop id, 
Add id int unsigned not null auto_increment first;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/web/87057.shtml
繁体地址,请注明出处:http://hk.pswp.cn/web/87057.shtml
英文地址,请注明出处:http://en.pswp.cn/web/87057.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Vue3 中 Excel 导出的性能优化与实战指南

文章目录 Vue3 中 Excel 导出的性能优化与实战指南引言:为什么你的导出功能会卡死浏览器?一、前端导出方案深度剖析1.1 xlsx (SheetJS) - 轻量级冠军1.2 exceljs - 功能强大的重量级选手 二、后端导出方案:大数据处理的救星2.1 为什么大数据需…

安卓RecyclerView实现3D滑动轮播效果全流程实战

安卓RecyclerView实现3D滑动轮播效果全流程实战 1. 前言 作为一名学习安卓的人,在接触之前和之后两种完全不同的想法: 好看和怎么实现 当初接触到RecyclerView就觉得这个控件就可以把关于列表的所有UI实现,即便不能,也是功能十分强大 放在现在依然是应用最广的滑动列表控…

电机控制——电机位置传感器零位标定

在有感FOC算法中电机位置是一个重要的输入,电机位置传感器的作用就是测量电机的旋转角度,通常是输出sin(Theta)和cos(Theta)两路模拟信号,根据这两路模拟信号测得电机旋转绝对角度。注意传感器测量的是机械角度,不是电角度。 关于…

生物化学(实验流程) PCR聚合酶链式反应: DNA 凝胶电泳实验原理 实验流程方法 实操建议笔记

凝胶电泳是分子生物学中最常用的技术之一,广泛用于 DNA 片段的可视化、分离与识别。在获取DNA 凝胶电泳相关设备(电泳设备 & DNA样品染料 & 凝胶 & 染料)之后,可以考虑进行电泳操作。 整体电泳操作流程(从…

Python应用指南:利用高德地图API获取公交+地铁可达圈(三)

副标题:基于模型构建器的批处理多份CSV转换为点、线、面图层 在地理信息系统(GIS)的实际应用中,我们经常需要处理大量以表格形式存储的数据,例如人口统计数据、兴趣点(POI)信息和监测站点记录等…

每日算法刷题Day38 6.25:leetcode前缀和3道题,用时1h40min

5. 1749.任意子数组和的绝对值的最大值(中等,学习) 1749. 任意子数组和的绝对值的最大值 - 力扣(LeetCode) 思想 1.给你一个整数数组 nums 。一个子数组 [numsl, numsl1, ..., numsr-1, numsr] 的 和的绝对值 为 abs(numsl numsl1 ... numsr-1 nu…

创客匠人视角下创始人 IP 打造的底层逻辑与实践路径

在知识付费行业蓬勃发展的当下,创始人 IP 已成为连接用户与商业价值的核心纽带。创客匠人创始人老蒋在与行业头部 IP 洪鑫的对话中揭示了一个关键命题:IP 打造的成败,始于发心与理念的根基。从洪鑫教育中心营收超 6000 万的案例来看&#xff…

2022/7 N2 jlpt词汇

気力(きりょく) 清く(きよく) 記録(きろく) 記憶(きおく) 賢い(かしこい) 偉い(えらい) 凄い(すごい) 鋭い&am…

系统性能优化-8 TCP缓冲区与拥塞控制

每个 TCP 连接都有发送缓冲区和接收缓冲区,发送缓冲区存已发送未确认数据和待发送数据,接收缓冲区存接收但是没有被上层服务读取的数据。 # cat /proc/net/sockstat sockets: used 1885 TCP: inuse 537 orphan 0 tw 3 alloc 959 mem 10其中 mem 代表当前…

【前端】vue工程环境配置

环境准备(Windows版本) nodejs安装 (base) PS C:\Users\Administrator> nvm install 18.8.0 (base) PS C:\Users\Administrator> nvm use 18.8.0 Now using node v18.8.0 (64-bit) (base) PS C:\Users\Administrator> npm -v 8.18.0 (base) PS C:\Users\Administrat…

什么是data version control?为什么需要它?它能解决什么问题?

Data Version Control (DVC) 是一个开源工具,专为数据科学和机器学习项目设计。它的核心目标是像 Git 管理代码一样来管理机器学习项目中的数据和模型文件。 简单来说,DVC 是什么? Git for Data & Models: 它扩展了 Git 的功…

简约计生用品商城简介

计生用品商城简介:uniapp结合thinkphp实现的全开源代码, 内置基本功能:1.后台商品excel一键导入 2.分销利润,按照利润加个分红

go中自动补全插件安装-gopls

vscode中安装gopls失败,导致go中代码无提示,无法自动补全引用 环境变量中设置go的代理:setx GOPROXY “https://goproxy.cn,direct”go install golang.org/x/tools/goplslatest

力扣寻找数组中心索引-性能优化思考

如下代码 var pivotIndex function(nums) {// 空数组返回-1if (nums.length 0) return -1// 计算数组总和const totalSum nums.reduce((sum, num) > sum num, 0);let leftSum 0;// 遍历数组查找中心索引for (let i 0; i < nums.length; i) {// 右侧和 总和 - 左侧…

SVN 分支管理(本文以Unity项目为例)

文章目录 1.准备工作2.新建SVN仓库2.拉取远端空 trunk 到Unity项目目录下3.设置忽略&#xff0c;提交unity项目至仓库3.创建分支4.切换分支5.合并分支回主干&#xff08;例如将 trunk_01 合并回 trunk&#xff09;5.删除分支&#xff08;可选&#xff09; 1.准备工作 下载Tort…

数据结构学习day6---流+读写函数+缓冲+定义函数

目录 1.标准io&#xff1b; stdio.h 1.1标准io的概念 1.2Linux操作系统当中IO都是对文件的操作 1.3标准IO&#xff1a;ANSI C 设计的一组用文件IO 封装的操作库函数 2.文件 2.1作用 2.2linux中文件的类型 3.man 5.流: FILE* 5.1流的定义 5.2流的分类 6.c语言文…

互联网医院,正在发生的医疗新变革

随着信息技术的飞速发展&#xff0c;互联网医院作为医疗服务的新形态&#xff0c;正在全球范围内迅速崛起。在中国&#xff0c;这一变革尤为显著&#xff0c;互联网医院不仅改善了医疗服务的可及性和便捷性&#xff0c;还极大地提升了医疗服务的质量和效率。 一、互联网医院的发…

rabbitmq动态创建交换机、队列、动态绑定,销毁

// 缓存已创建的绑定&#xff0c;避免重复声明private final Map<String, Date> createdBindings new ConcurrentHashMap<>(); public void createAndBindQueueToExchange(String type,String clinetId, String routingKey) {String queueName routingKey;lo…

云效代码仓库导入自建gitlab中

登录自建GitLab 在浏览器中输入GitLab访问地址http://192.168.1.111:81/users/sign_in&#xff0c;输入账号和密码登录GitLab服务&#xff0c;如下图&#xff1a; 新建一个空的代码库 按照以下截图顺序&#xff0c;创建一个新的空项目&#xff0c;如下&#xff1a; 克隆镜像 …

业界优秀的零信任安全管理系统产品介绍

腾讯 iOA 零信任安全管理系统 简介&#xff1a;腾讯 iOA 零信任安全管理系统是腾讯终端安全团队针对企业安全上云和数字化转型&#xff0c;提供的企业网络边界处的应用访问管控系统&#xff0c;为企业应用提供统一、安全、高效的访问入口&#xff0c;同时提供终端安全加固、软…