Auto increment a value on the fly with MySQL

本文介绍了如何在MySQL中使用自增变量实现查询和更新操作。通过设置变量并结合SELECT和UPDATE语句,可以轻松地为查询结果添加自增序号或将表中的某列更新为自增数值。

SELECT with auto incrementing value

To have an auto incrementing value, first assign a variable like so:

SELECT @i:=0;

This can now be incremented in the SELECT query like so:

SELECT *, @i:=@i+1 AS i FROM fruit ORDER BY name;

This will return:

+----------+--------+-----------+------+
| fruit_id | name   | somevalue | i    |
+----------+--------+-----------+------+
|        4 | Apple  |         0 |    1 |
|        1 | Banana |         0 |    2 |
|        3 | Cherry |         0 |    3 |
|        2 | Orange |         0 |    4 |
+----------+--------+-----------+------+

Notice that for each record, i is one greater than the previous record.

UPDATE with auto incrementing value

The next example updates the "somevalue" column with an incrementing value. Note that @i needs to be reset otherwise it will continue in this example with 5 being the next number.

SELECT @i:=0;

As with the SELECT query above, we'll update ordering by name:

UPDATE fruit SET somevalue = @i:=@i+1 ORDER BY name;

And the result from "SELECT * FROM fruit"

+----------+--------+-----------+
| fruit_id | name   | somevalue |
+----------+--------+-----------+
|        1 | Banana |         2 |
|        2 | Orange |         4 |
|        3 | Cherry |         3 |
|        4 | Apple  |         1 |
+----------+--------+-----------+

or "SELECT * FROM fruit ORDER BY name"

+----------+--------+-----------+
| fruit_id | name   | somevalue |
+----------+--------+-----------+
|        4 | Apple  |         1 |
|        1 | Banana |         2 |
|        3 | Cherry |         3 |
|        2 | Orange |         4 |
+----------+--------+-----------+


转载于:https://my.oschina.net/vincentcuhk/blog/620218

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值