【问题标题】:how to repeat serial number in mysql table如何在mysql表中重复序列号
【发布时间】:2013-10-12 11:40:10
【问题描述】:

我有下面的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

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我尝试生成序列号但无法重复
  • 当您选择数据时,这在 MySQL 中模拟 RANK() OVER PARTITION 时是可能的,但您需要使用用户变量,但如果表包含大量记录,这对于 MySQL 来说是一个繁重的查询。 /跨度>

标签: mysql serial-number


【解决方案1】:

来,试试看:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多