如何在 MySQL 中选择增量计数器?
要在 MySQL 中选择增量计数器,首先需要声明并初始化一个变量。语法如下 -
set @anyVariableName=0; select yourColumnName, @anyVariableName:=@anyVariableName+1 as anyVariableName from yourTableName;
为了理解上述语法并设置增量计数器,我们首先创建一个表。创建表的查询如下。
mysql> create table incrementCounterDemo -> ( -> Name varchar(100) -> ); Query OK, 0 rows affected (1.01 sec)
使用 insert 命令在表中插入一些记录。查询如下。
mysql> insert into incrementCounterDemo values('John'); Query OK, 1 row affected (0.18 sec) mysql> insert into incrementCounterDemo values('Carol'); Query OK, 1 row affected (0.20 sec) mysql> insert into incrementCounterDemo values('David'); Query OK, 1 row affected (0.14 sec) mysql> insert into incrementCounterDemo values('Mike'); Query OK, 1 row affected (0.21 sec) mysql> insert into incrementCounterDemo values('Bob'); Query OK, 1 row affected (0.12 sec) mysql> insert into incrementCounterDemo values('Sam'); Query OK, 1 row affected (0.16 sec)
使用 select 语句从表中显示所有记录。查询如下 -
mysql> select *from incrementCounterDemo;
以下是输出。
+-------+ | Name | +-------+ | John | | Carol | | David | | Mike | | Bob | | Sam | +-------+ 6 rows in set (0.00 sec)
设置变量
mysql> set @counter=0; Query OK, 0 rows affected (0.00 sec)
现在选择增量计数器。
mysql> select Name, -> @counter:=@counter+1 as IncrementingValuebyOne -> from incrementCounterDemo;
以下是输出。
+-------+------------------------+ | Name | IncrementingValuebyOne | +-------+------------------------+ | John | 1 | | Carol | 2 | | David | 3 | | Mike | 4 | | Bob | 5 | | Sam | 6 | +-------+------------------------+ 6 rows in set (0.00 sec)
广告