如何在 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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP