在这里,试一试:
select name, city, serial_number from
(select name, city
, (case when @city <> city then @citynum := 1 else @citynum := @citynum + 1 end) as serial_number
, (case when @city <> city then @city := city end) as v
from tbl_cities, (select @citynum := 0, @city := '') as c
order by city) as cities
这是您运行的示例的链接:http ://sqlfiddle.com/#!2/615f5/1 。
您需要将“tbl_cities”更改为您的表格名称。
我无法将它保存为视图或在更新语句中使用,因为它使用变量。一种快速的方法是使用上面的 select 语句创建一个新表并在添加新数据时定期运行。
drop table if exists tbl_cities_serial;
create table tbl_cities_serial(select name, city, serial_number from
(select name, city
, (case when @city <> city then @citynum := 1 else @citynum := @citynum + 1 end) as serial_number
, (case when @city <> city then @city := city else @city end) as v
from tbl_cities, (select @citynum := 0, @city := '') as c
order by city) as cities)