1、原理实现
待补充。
2、设置主键自动增加
MS SQLServer
在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包含两个参数,第一个参数表示起始值,第二个参数表示增量。
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数据库会自动按递增的方式为主键赋值。
图形化展现方式: