当值改变时,MySQL增加用户变量

时间:2012-08-03 21:46:43

标签: mysql statistics increment intervals user-variables

我有一个由多个组组成的表,例如每组五行。每个组中的每一行都拥有该组唯一的date值。

我想在查询中执行的操作是遍历表,并在此date值更改时递增用户变量(@count)。也就是说,@ count应该等于组计数,而不是行数。

我目前的查询是这样的,如果你想知道:

SELECT @row := @row +1 AS rownum, date
FROM ( SELECT @row := 0 ) r, stats

非常感谢。

2 个答案:

答案 0 :(得分:3)

这样的事情怎么样?

SELECT 
    (CASE WHEN @date <> date THEN @row := @row +1 ELSE @row END) AS rownum, 
    @date:= date, 
    date
FROM ( SELECT @row := 0, @date := NOW() ) r, stats

答案 1 :(得分:2)

您不需要用户变量来回答您正在执行的查询。您是否有理由使用用户变量(例如,模拟排名函数?)

如果不是:

-- how many groups are there?
select count(distinct date) distinct_groups from table;

-- each group and count of rows in the group
select date, count(*) from table group by date;

-- if you want the Nth row from each group, assuming you have an auto_increment called id:
select *
  from table
  join ( select date, max(id) id
           from table
          group by date
  ) sq
  on table.id = sq.id