MySQL简单的select语句,如果行值不同于前一个,则创建自动增量

时间:2017-07-08 19:17:29

标签: mysql sql

到目前为止,我有以下查询:

SET @cnt = 0;
SELECT (
  @cnt := @cnt +1
) AS rowNumber, brand
FROM  `cars` 

输出以下内容:

rowNumber | brand
1         | fiat
2         | fiat
3         | fiat
4         | bmw
5         | bmw
6         | mercedes
7         | mercedes
8         | tesla
9         | tesla

但是我希望实现:

rowNumber | brand
1         | fiat
1         | fiat
1         | fiat
2         | bmw
2         | bmw
3         | mercedes
3         | mercedes
4         | tesla
4         | tesla

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用其他变量执行此操作:

select (@rn := if(@b = brand, @rn,
                  if(@b := brand, @rn + 1, @rn + 1)
                 )
       ) as rowNumber, brand
from `cars` c cross join
     (select @b := '', @rn := 0) params
order by brand;