【MYSQL中(@i:=@i+1)的使用】

@TOC

1.(@i:=@i+1)的作用

1.查询sql时,有时需要一个伪列rownum。在mysql中便可以使用(@i:=@i+1)生成自增的序列

例子

SELECT (@i:=@i+1) rownum,first_name,last_name  FROM employee ,(SELECT (@i:=0)) t

在这里插入图片描述

从结果可以看出rownum每次都增加1.如果想要加5,便改为(@i:=@i+5).如果想要从100开始,便将(@i:=0)改为(@i:=100)
SELECT (@i:=@i+5) rownum ,first_name,last_name FROM employee, (SELECT (@i:=0)) t

在这里插入图片描述

SELECT (@i:=@i+1) rownum ,first_name,last_name FROM employee, (SELECT (@i:=100)) t

在这里插入图片描述

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
This is a MySQL query that selects the student ID (s_id), assigns a sequential number to each row (i), and calculates the rank of each student based on their sum of scores (sum_score). The query uses a subquery to first group the scores by student ID and calculate the sum of scores for each student. This subquery is then joined with a variable initialization subquery that sets the initial values of @k, @i, and @score to 0. The variable @k is used to keep track of the current rank while iterating over the rows. The variable @i is used to assign a sequential number to each row. The variable @score is used to compare the sum_score of the current row with the sum_score of the previous row. The CASE statement is used to check if the sum_score of the current row is equal to the sum_score of the previous row. If they are equal, then the rank remains the same. If they are not equal, then the rank is updated to the current sequential number. Here is a breakdown of the query: ``` SELECT a.s_id, -- Select the student ID @i:=@i+1 AS i, -- Assign a sequential number to each row @k:=(case when @score=a.sum_score then @k else @i end) as rank, -- Calculate the rank a.sum_score AS score -- Select the sum of scores for each student FROM (SELECT s_id,SUM(s_score) AS sum_score FROM score GROUP BY s_id ORDER BY sum_score DESC) a, -- Subquery to calculate sum of scores for each student (SELECT @k:=0,@i:=0,@score:=0) s -- Subquery to initialize variables ``` Note that the use of variables in this query is not recommended, as it can lead to unexpected results if the variables are not reset properly. It is better to use a subquery or a window function to calculate the rank.
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值