search
HomeDatabaseMysql TutorialMySQL实现相仿Oracle的序列

MySQL实现类似Oracle的序列 Oracle一般使用序列(Sequence)来处理主键字段,而MySQL则提供了自增长(increment)来实现类的目的; 但在实际使用过程中发现,MySQL的自增长有诸多的弊端:不能控制步长、开始索引、是否循环等;若需要迁移数据库,则对于主键这块,

MySQL实现类似Oracle的序列

Oracle一般使用序列(Sequence)来处理主键字段,而MySQL则提供了自增长(increment)来实现类似的目的;
但在实际使用过程中发现,MySQL的自增长有诸多的弊端:不能控制步长、开始索引、是否循环等;若需要迁移数据库,则对于主键这块,也是个头大的问题。
本文记录了一个模拟Oracle序列的方案,重点是想法,代码其次。
Oracle序列的使用,无非是使用.nextval和.currval伪列,基本想法是:1、MySQL中新建表,用于存储序列名称和值;2、创建函数,用于获取序列表中的值;
具体如下:

表结构为

表结构为:
drop table if exists sequence;
create table sequence (
	seq_name		VARCHAR(50)	NOT NULL, -- 序列名称
	current_val		INT			NOT NULL, --当前值
	increment_val	INT			NOT NULL	DEFAULT 1, --步长(跨度)
	PRIMARY KEY (seq_name)
);
实现currval的模拟方案

create function currval(v_seq_name VARCHAR(50))
returns integer
begin
	declare value integer;
	set value = 0;
	select current_value into value
	from sequence
	where seq_name = v_seq_name;
	return value;
end;
函数使用为:select currval('MovieSeq');


实现nextval的模拟方案
create function nextval (v_seq_name VARCHAR(50))
return integer
begin
  update sequence
  set current_val = current_val + increment_val
  where seq_name = v_seq_name;
  return currval(v_seq_name);
end;
函数使用为:select nextval('MovieSeq');

增加设置值的函数

create function setval(v_seq_name VARCHAR(50), v_new_val INTEGER)
returns integer
begin
  update sequence
  set current_val = v_new_val
  where seq_name = v_seq_name;
return currval(seq_name);

同理,可以增加对步长操作的函数,在此不再叙述。

以上代码未经测试,仅仅是想表达一个想法而已。

PS:在网上看到另外两人的博文,表达了同样的意思,将连接贴出来,供大家比较。

http://hi.baidu.com/sue_spring/item/6dada80adfb98e97a3df43bb

http://meetrice.iteye.com/blog/89426


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.