Home Database Mysql Tutorial 深入Mysql,SqlServer,Oracle主键自动增长的设置详解_MySQL

深入Mysql,SqlServer,Oracle主键自动增长的设置详解_MySQL

Jun 01, 2016 pm 01:24 PM
mysql oracle database

bitsCN.com 1、把主键定义为自动增长标识符类型
MySql
在mysql中,如果把表的主键设为auto_increment类型,数据库就会自动为主键赋值。例如:

create table customers(id int auto_increment primary key not null, name varchar(15));
insert into customers(name) values("name1"),("name2");
select id from customers;

以上sql语句先创建了customers表,然后插入两条记录,在插入时仅仅设定了name字段的值。最后查询表中id字段,查询结果为:

由此可见,一旦把id设为auto_increment类型,mysql数据库会自动按递增的方式为主键赋值。
Sql Server
在MS SQLServer中,如果把表的主键设为identity类型,数据库就会自动为主键赋值。例如:

create table customers(id int identity(1,1) primary key not null, name varchar(15));
insert into customers(name) values('name1'),('name2');
select id from customers;

注意:在sqlserver中字符串用单引号扩起来,而在mysql中可以使用双引号。
查询结果和mysql的一样。



由此可见,一旦把id设为identity类型,MS SQLServer数据库会自动按递增的方式为主键赋值。identity包含两个参数,第一个参数表示起始值,第二个参数表示增量。
PS:2013-6-4
以前经常会碰到这样的问题,当我们删除了一条自增长列为1的记录以后,再次插入的记录自增长列是2了。我们想在插入一条自增长列为1的记录是做不到的。今天跟同事讨论的时候发现可以通过设置SET IDENTITY_INSERT ON;来取消自增长,等我们插入完数据以后在关闭这个功能。实验如下:

use TESTDB2
--step1:创建表
create table customers(
    id int identity primary key not null,
    name varchar(15)
);
--step2:执行插入操作
insert into customers(id,name) values(1,'name1');
--报错:An explicit value for the identity column in table 'customers' can only be specified when a column list is used and IDENTITY_INSERT is ON.
--step3:放开主键列的自增长
SET IDENTITY_INSERT customers ON;
--step4:插入两条记录,主键分别为1和3。插入成功
insert into customers(id,name) values(1,'name1');
insert into customers(id,name) values(3,'name1');
--step5:再次插入一个主键为2的记录。插入成功
insert into customers(id,name) values(2,'name1');
--step6:插入重复主键,
--报错:Violation of PRIMARY KEY constraint 'PK__customer__3213E83F00551192'. Cannot insert duplicate key in object 'dbo.customers'.
insert into customers(id,name) values(3,'name1');
--step7:关闭IDENTITY_INSERT
SET IDENTITY_INSERT customers OFF;

2、从序列中获取自动增长的标识符
Oracle
在Oracle中,可以为每张表的主键创建一个单独的序列,然后从这个序列中获取自动增加的标识符,把它赋值给主键。例如一下语句创建了一个名为customer_id_seq的序列,这个序列的起始值为1,增量为2。

create sequence customer_id_seq increment by 2 start with 1

一旦定义了customer_id_seq序列,就可以访问序列的curval和nextval属性。
•curval:返回序列的当前值
•nextval:先增加序列的值,然后返回序列值
以下sql语句先创建了customers表,然后插入两条记录,在插入时设定了id和name字段的值,其中id字段的值来自于customer_id_seq序列。最后查询customers表中的id字段。

create table customers(id int primary key not null, name varchar(15));
insert into customers values(customer_id_seq.nextval, 'name1');
insert into customers values(customer_id_seq.nextval, 'name2');
select id from customers;

如果在oracle中执行以上语句,查询结果为:



通过触发器自动添加id字段
从上述插入语句可以发现,如果每次都要插入customer_id_seq.nextval的值会非常累赘与麻烦,因此可以考虑使用触发器来完成这一步工作。
创建触发器trg_customers

create or replace
trigger trg_customers before insert on customers for each row
begin
select CUSTOMER_ID_SEQ.nextval into :new.id from dual;
end;

插入一条记录

insert into customers(name) values('test');

这是我们会发现这一条记录被插入到数据库中,并且id还是自增长的。

bitsCN.com
Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How does Go WebSocket integrate with databases? How does Go WebSocket integrate with databases? Jun 05, 2024 pm 03:18 PM

How to integrate GoWebSocket with a database: Set up a database connection: Use the database/sql package to connect to the database. Store WebSocket messages to the database: Use the INSERT statement to insert the message into the database. Retrieve WebSocket messages from the database: Use the SELECT statement to retrieve messages from the database.

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to delete data from MySQL table using PHP? How to delete data from MySQL table using PHP? Jun 05, 2024 pm 12:40 PM

PHP provides the following methods to delete data in MySQL tables: DELETE statement: used to delete rows matching conditions from the table. TRUNCATETABLE statement: used to clear all data in the table, including auto-incremented IDs. Practical case: You can delete users from the database using HTML forms and PHP code. The form submits the user ID, and the PHP code uses the DELETE statement to delete the record matching the ID from the users table.

See all articles