MySQL 中 SQL Server IDENTITY 列的等效项?
mysqlmysqli database更新于 2024/2/27 5:49:00
MySQL 中 Microsoft SQL Server IDENTITY 列的等效项是 AUTO_INCREMENT。SQL Server 中的 IDENTITY 的作用类似于 MySQL 中的 AUTO_INCREMENT。
语法如下 −
CREATE TABLE yourTableName ( yourColumnName1 dataType NOT NULL AUTO_INCREMENT, yourColumnName2 dataType, . . . N, PRIMARY KEY(yourColumnName1) );
在 MySQL 中,如果你的列是 auto_increment,则需要使用主键,否则 MySQL 将给出错误。查看错误 −
mysql> create table EquivalentOfIdentityInMySQL -> ( -> ProductId int NOT NULL AUTO_INCREMENT, -> ProductName varchar(30) -> ); ERROR 1075 (42000) − Incorrect table definition; there can be only one auto column and it must be defined as a key
要消除上述错误,您需要将 ProductId 设为主键。MySQL AUTO_INCREMENT 的声明如下,将 ProductId 设为主键 −
mysql> create table EquivalentOfIdentityInMySQL -> ( -> ProductId int NOT NULL AUTO_INCREMENT, -> ProductName varchar(30) -> , -> PRIMARY KEY(ProductId) -> ); Query OK, 0 rows affected (0.59 sec)
如果您不为 ProductId 列传递任何值,MySQL 将从 1 开始自动递增,下一个数字默认递增 1。
要检查 ProductId 列,让我们使用 insert 命令在表中插入一些记录。查询如下−
mysql> insert into EquivalentOfIdentityInMySQL(ProductName) values('Product-1'); Query OK, 1 row affected (0.14 sec) mysql> insert into EquivalentOfIdentityInMySQL(ProductName) values('Product-2'); Query OK, 1 row affected (0.14 sec) mysql> insert into EquivalentOfIdentityInMySQL(ProductName) values('Product-34'); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from EquivalentOfIdentityInMySQL;
以下是输出 −
+-----------+-------------+ | ProductId | ProductName | +-----------+-------------+ | 1 | Product-1 | | 2 | Product-2 | | 3 | Product-34 | +-----------+-------------+ 3 rows in set (0.00 sec)
查看 ProductId 列,我们没有为该列传递任何值,但我们获取的数字从 1 开始,下一个数字以 1 为增量。