Har*_*ana 1 mysql sql database
我有下表
id name address empid
1 AA aa 0
2 BB bb 0
3 CC cc 0
Run Code Online (Sandbox Code Playgroud)
我需要编写一个查询来设置empid从1开始.请如何编写它.我必须使用存储过程,还是可以使用普通查询?
谢谢.
这是一种利用MySQL中非常模糊的赋值运算符的方法.在主键序列中存在间隙的情况下,该解决方案不会像其他一些解决方案那样跳过数字.
set @count = 0;
update test set empid = @count := @count+1;
Run Code Online (Sandbox Code Playgroud)
这是证明:
mysql> create table test (
-> id int unsigned primary key auto_increment,
-> name varchar(32) not null,
-> address varchar(32) not null,
-> empid int unsigned not null default 0
-> ) engine=innodb;
Query OK, 0 rows affected (0.02 sec)
mysql> insert into test (name, address)
-> values ('AA', 'aa'), ('BB', 'bb'), ('CC', 'cc');
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from test;
+----+------+---------+-------+
| id | name | address | empid |
+----+------+---------+-------+
| 1 | AA | aa | 0 |
| 2 | BB | bb | 0 |
| 3 | CC | cc | 0 |
+----+------+---------+-------+
3 rows in set (0.00 sec)
mysql> set @count=0;
Query OK, 0 rows affected (0.00 sec)
mysql> update test set empid = @count := @count+1;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3 Changed: 3 Warnings: 0
mysql> select * from test;
+----+------+---------+-------+
| id | name | address | empid |
+----+------+---------+-------+
| 1 | AA | aa | 1 |
| 2 | BB | bb | 2 |
| 3 | CC | cc | 3 |
+----+------+---------+-------+
3 rows in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)