2013-10-12 69 views
0

我有以下MySQL表如何重複序列號在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 
+0

你到目前爲止嘗試了什麼? –

+0

我嘗試生成序列號但無法重複輸入 – user2021672

+0

當您選擇數據時,在模擬MySQL中的RANK()OVER PARTITION時可能會出現這種情況,但您需要使用用戶變量,但如果表包含很多記錄 –

回答

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)