id更改时如何将用户定义的变量值设置为零?

时间:2019-05-02 03:06:33

标签: mysql sql

在以下查询中,只要ID发生更改,我都会尝试将变量值设置为零。

我正在尝试在单个查询中实现此目标,而不会出现性能问题。 因为在实际查询中它具有10,000多个记录。 这是我到目前为止所拥有的,

样品表:

       create table Test(id integer, title varchar(100));
       insert into Test(id, title) values(1, "Hello");
       insert into Test(id, title) values(1, "Hello");
       insert into Test(id, title) values(1, "Hello");
       insert into Test(id, title) values(1, "Hello");
       insert into Test(id, title) values(2, "Hello");
       insert into Test(id, title) values(2, "Hello");
       insert into Test(id, title) values(1, "Hello");

这是我的查询:

    select a0.id,a0.title,@a:=@a+a0.id as val from
    (select * from Test order by id) as a0 
    left join
    (select id, @a:=0 from Test group by id) as a1
     on
    a0.id=a1.id

-执行上述查询后得到的输出:

+----+-------+-----+
| id | title | val |
+----+-------+-----+
|  1 | Hello |   1 |
|  1 | Hello |   2 |
|  1 | Hello |   3 |
|  1 | Hello |   4 |
|  1 | Hello |   5 |
|  2 | Hello |   7 |
|  2 | Hello |   9 |
+----+-------+-----+

-我要实现的目标:

+----+-------+-----+
| id | title | val |
+----+-------+-----+
|  1 | Hello |   1 |
|  1 | Hello |   2 |
|  1 | Hello |   3 |
|  1 | Hello |   4 |
|  1 | Hello |   5 |
|  2 | Hello |   2 |
|  2 | Hello |   4 |
+----+-------+-----+

1 个答案:

答案 0 :(得分:0)

使用另一个变量保存上一行的ID。然后,您可以测试当前ID是否相同。

更改后,将@a重设为当前ID(而不是0)。

SELECT a0.id, a0.title, @a := IF(a0.id = @last_id, @a + a0.id, a0.id) AS val, @last_id := a0.id
FROM (SELECT * FROM Test ORDER BY id) AS a0
CROSS JOIN (SELECT @a := 0, @last_id := null) AS vars

DEMO