MySQL序列
概述
序列是通常用于生成唯一标识符的有序数字列表。MySQL没有原生的SEQUENCE对象,但可以使用AUTO_INCREMENT或替代方法实现序列。
序列方法
AUTO_INCREMENT:主键自增 自定义序列表:用户定义的序列表 函数:LAST_INSERT_ID()等 触发器:生成序列值
AUTO_INCREMENT / AUTO_INCREMENT
基本AUTO_INCREMENT
sql
-- Create table with auto increment
-- Insert and auto ID assigned
-- Get last insert IDAUTO_INCREMENT选项
sql
-- Set starting value
-- Modify starting value
-- Reset auto increment
-- Check next valueAUTO_INCREMENT间隙
sql
-- Auto increment creates gaps when records deleted
-- Example:
-- Records: 1, 2, 3, 4, 5
-- Delete 3, 4
-- Next insert: 6 (not 3)
-- Get gaps自定义序列表
创建序列表
sql
-- Create sequence table
-- Initialize sequences获取下一个序列值
sql
-- Method 1: UPDATE and SELECT (simple)
-- Get next value
-- Method 2: Transaction-safe method序列的存储过程
sql
-- Use procedure
-- Multiple calls序列函数
LAST_INSERT_ID() / LAST_INSERT_ID()
sql
-- Get last auto increment ID
-- Per connection
-- Each connection maintains its own value
-- Use in transactions生成序列
sql
-- Generate sequence in query
-- Generate sequence with variables高级序列
复合序列
sql
-- Create sequence with multiple components
-- Initialize daily sequences
-- Get today's sequence带前缀的序列
sql
-- Combine sequence with prefix
-- Store as string
-- Insert with sequence序列性能
优化序列
sql
-- Use appropriate data types
-- INT: Up to 2 billion
-- BIGINT: For very large sequences
-- Use LOCK IN SHARE MODE
-- Minimize lock time序列缓存
sql
-- Cache multiple sequence values
-- Get cached values
-- Update to next cache start
-- Use cached values in application
-- @start_val to @start_val + @cache_size - 1实用示例
示例1:订单号
sql
-- Generate formatted order numbers
-- Get sequence
-- Format: ORD-YYYYMM-XXXXX
-- Insert order
-- Use procedure示例2:发票号
sql
-- Year-based sequence
-- Initialize for current year
-- Generate invoice number示例3:批量序列生成
sql
-- Generate multiple sequence values
-- Generate sequence for 100 items
-- ... up to 100
-- Update sequence
-- Use generated sequence序列触发器
使用触发器的自增
sql
-- Create custom sequence table
-- Create table without AUTO_INCREMENT
-- Trigger to generate ID
-- Insert items序列比较
AUTO_INCREMENT与自定义序列
| 功能 | AUTO_INCREMENT | Custom Sequence |
|---|---|---|
| 简单性 | Simple / 简单 | Requires more code / 需要更多代码 |
| 间隙 | Can have gaps / 可能有间隙 | Can control / 可以控制 |
| 多表 | One per table / 每表一个 | Shared / 共享 |
| 事务 | Automatic / 自动 | Manual / 手动 |
| 性能 | Optimized / 优化 | Slightly slower / 稍慢 |
最佳实践
选择序列方法
sql
-- Use AUTO_INCREMENT when:
-- - Simple sequential IDs needed
-- - Each table has own sequence
-- - Gaps are acceptable
-- Use custom sequence when:
-- - Shared sequence across tables
-- - Need specific format (ORD-XXXX)
-- - Need to control gaps
-- - Need year/month-based sequences错误处理
sql
-- Safe sequence procedure小结
MySQL序列提供:
AUTO_INCREMENT:简单、每表序列 自定义序列:灵活、跨表共享 函数:LAST_INSERT_ID()用于自增 存储过程:封装序列逻辑 触发器:自动生成ID
根据唯一标识符的需求选择适当的方法。
上一个:元数据
下一个:处理重复数据