如何在 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)

更新時間:2020 年 6 月 25 日

6 千次瀏覽

開啟你的職業生涯

參加課程以獲得認證

開始
廣告
© . All rights reserved.