2014-02-18 28 views
0

我有一個名稱,屬性ab,然後cluster的MySQL表。如何在MySQL表中添加具有計數值的列?

+--------+-----------+----------+---------+ 
| names | a   | b  | cluster | 
+--------+-----------+----------+---------+ 
| Johny | 225630096 |  447 |  3 | 
| Johny | 225630118 |  491 |  4 | 
| Johny | 225630206 |  667 |  5 | 
| Johny | 225630480 |  1215 |  6 | 
| Johny | 225630677 |  1609 |  7 | 
| Johny | 225631010 |  2275 |  8 | 
| Manny | 154247076 |  6235 |  1 | 
| Manny | 154247079 |  6241 |  1 | 
| Manny | 154247083 |  6249 |  1 | 
| Manny | 154247084 |  6251 |  1 | 
| Manny | 154247087 |  6257 |  1 | 
| Manny | 154247090 |  6263 |  1 | 
| Manny | 154247091 |  6265 |  1 | 
| Manny | 154247093 |  6269 |  1 | 
| Manny | 154247097 |  6277 |  1 | 
| Manny | 154247098 |  6279 |  1 | 
| Manny | 154247099 |  6281 |  1 | 
| Manny | 154247100 |  6283 |  1 | 
| Manny | 154247555 |  7193 |  2 | 
| Manny | 154247629 |  7341 |  3 | 
| Manny | 154247630 |  7343 |  3 | 
| Manny | 154247633 |  7349 |  3 | 
| Manny | 154247634 |  7351 |  3 | 
| Douges | 146340582 |  6811 |  1 | 

我想添加基於namesclustercount列。例如,輸出將包含每個名稱內的簇數。例如,輸出將是這個樣子:

+--------+-----------+----------+---------+---------+ 
| names | a   | b  | cluster |count | 
+--------+-----------+----------+---------+---------+ 
| Johny | 225630096 |  447 |  3 | 1 | 
| Johny | 225630118 |  491 |  4 | 2 | 
| Johny | 225630206 |  667 |  5 | 3 | 
| Johny | 225630480 |  1215 |  6 | 4 | 
| Johny | 225630677 |  1609 |  7 | 5 | 
| Johny | 225631010 |  2275 |  8 | 6 | 
| Manny | 154247076 |  6235 |  1 | 1 | 
| Manny | 154247079 |  6241 |  1 | 1 | 
| Manny | 154247083 |  6249 |  1 | 1 | 
| Manny | 154247084 |  6251 |  1 | 1 | 
| Manny | 154247087 |  6257 |  1 | 1 | 
| Manny | 154247090 |  6263 |  1 | 1 | 
| Manny | 154247091 |  6265 |  1 | 1 | 
| Manny | 154247093 |  6269 |  1 | 1 | 

我曾嘗試使用COUNT功能,但是,它似乎計算集羣的數量來代替。

+1

你對[count()](https://dev.mysql.com/doc/refman/5.1/en/counting-rows.html)有RTFM嗎?你想要的東西不能直接用mysql來完成,但可以使用select中的局部變量僞裝。 'select if(@prev_name <> names,@count:= 1,@count:= @ count + 1)AS count ...' –

+0

你認爲使用python做這件事可能更有意義嗎? – msakya

+0

它肯定會使查詢更容易維護。 –

回答

0

你可以用子查詢或變量來做到這一點。這些變量通常更有效:

select t.*, 
     @rn := if(@name = name and @cluster = cluster, @rn, if(@name = name, @rn + 1, 1)) as `count`, 
     @name := name, @cluster := cluster 
from table t cross join 
    (select @rn := 0, @name := '', @cluster := -1) const 
order by name, cluster; 

如果你想把這爲表(而不是從查詢結果)使用create table asinsert into

子查詢的方法是:

select t.*, 
     (select count(distinct cluster) 
     from table t2 
     where t2.name = t.name and 
       t2.cluster <= t.cluster 
     ) as `count` 
from table t; 

性能應該確定與table(name, cluster)的索引。請注意,這個版本可以在視圖中使用。

+0

謝謝戈登。但變量方法給了我一個語法錯誤。我試圖確保製表符與編寫的相同,但仍然在 處發生錯誤''您的SQL語法錯誤;檢查與您的MySQL服務器版本對應的手冊,以便在'table t cross join'(在第1行選擇@rn:= 0,@name:='',@cluster:= -1'')附近使用正確的語法' 並在子查詢的方法,什麼表t2? 謝謝 – msakya

+0

@mshakya ...「表」應該是你的表名,這就是SQL的工作原理。 –

相關問題