博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Auto increment a value on the fly with MySQL
阅读量:5731 次
发布时间:2019-06-18

本文共 1641 字,大约阅读时间需要 5 分钟。

hot3.png

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 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

你可能感兴趣的文章
ubuntu常见问题汇聚
查看>>
MDLog分析
查看>>
Python3 django2.0 字段加密 解密 AES
查看>>
CCNA实验之:网络地址转换(NAT)实验
查看>>
【转】Python 可视化神器-Plotly Express
查看>>
计算机网络原理笔记-停止等待协议
查看>>
topcoder srm 662 div1
查看>>
Java基础之静态变量
查看>>
更换好的yum源
查看>>
NET牛人应该知道些什么?
查看>>
[Asp.Net web api]基于自定义Filter的安全认证
查看>>
洛谷P3763 [TJOI2017]DNA(后缀自动机)
查看>>
确定当前记录和下一条记录之间相差的天数
查看>>
NYOJ32:组合数(DFS入门)
查看>>
使用Callable和Future接口创建线程
查看>>
BZOJ 2568 比特集合
查看>>
sql语句返回主键SCOPE_IDENTITY()
查看>>
MongoDB培训
查看>>
机器学习开源项目精选TOP30
查看>>
python基础===对字符串进行左右中对齐
查看>>