当前位置:网站首页>Display line number in MySQL query result

Display line number in MySQL query result

2022-06-13 03:29:00 TRX1024

How to get a line number ? The key : Custom variable @rowNum:=0;

Suppose there is such data

mysql> select id,name from students;
+----+----------+
| id | name     |
+----+----------+
|  1 | zhangsan |
|  2 | lisi     |
|  3 | wangwu   |
|  4 | trx      |
|  5 | pjf      |
|  6 | wzm      |
+----+----------+

Look again

mysql> SELECT @rowNum:=0;
+------------+
| @rowNum:=0 |
+------------+
|          0 |
+------------+

mysql> SELECT @rowNum:=1;
+------------+
| @rowNum:=1 |
+------------+
|          1 |
+------------+

SELECT @rowNum:=0; Means to declare a name rowNum And assign it to 0, The variable name is customized , stay sql We can calculate this variable in , Such as :

mysql> select (@rowNum:[email protected]+1) as num from (SELECT @rowNum:=0) a;
+------+
| num  |
+------+
|    1 |
+------+

mysql> select (@rowNum:[email protected]+5) as num from (SELECT @rowNum:=0) a;
+------+
| num  |
+------+
|    5 |
+------+

here (SELECT @rowNum:=0) a Equivalent to a temporary table , If you compare it with students Join the tables and you will get :

mysql> select b.*,id,name from students a,(SELECT @rowNum:=0) b;
+------------+----+----------+
| @rowNum:=0 | id | name     |
+------------+----+----------+
|          0 |  1 | zhangsan |
|          0 |  2 | lisi     |
|          0 |  3 | wangwu   |
|          0 |  4 | trx      |
|          0 |  5 | pjf      |
|          0 |  6 | wzm      |
+------------+----+----------+

You can see ,b The table has only one piece of data , And a After the tables are connected, there are a Tabular 6 Data , If we set the custom variable @rowNum: Conduct +1 operation , What effect will it have ?

mysql> select (@rowNum:[email protected]+1) as num,id,name from students a,(SELECT @rowNum:=0) b;
+------+----+----------+
| num  | id | name     |
+------+----+----------+
|    1 |  1 | zhangsan |
|    2 |  2 | lisi     |
|    3 |  3 | wangwu   |
|    4 |  4 | trx      |
|    5 |  5 | pjf      |
|    6 |  6 | wzm      |
+------+----+----------+
6 rows in set (0.00 sec)

This achieves the purpose of query results with line numbers , Let's deduce the process of joining two tables :

  1. Start with custom variables @rowNum:=0,a Table 1 data (1,'zhangsan') And custom variables join, But we took @rowNum:[email protected]+1, namely 0+1, Then you will finally get (1,1,'zhangsan')
  2. At this point, the custom variable @rowNum:=1,a Table 1 data (2,'lisi') And custom variables join, namely 1+1, Then you finally get (2,2,'lisi')
  3. ....( And so on )

thus , We can get sql Query the result with line number .

原网站

版权声明
本文为[TRX1024]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280529583285.html