0

我有以下 mysql 表

 name   city
umar     mzd
ali      mzd
john     bagh
saeed    bagh
irum     bagh

我想以当城市名称更改时序列号重复的方式添加序列号,如下所示

S.No   name     city
  1    umar      mzd
  2    ali       mzd
  1   john      bagh
  2   saeed     bagh
  3   irum      bagh
4

1 回答 1

0

在这里,试一试:

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)
于 2013-10-12T22:00:02.953 回答