计算重复的列并更新计数器列

时间:2019-04-08 22:42:34

标签: mysql sql

Report table Columns:
ID | ipaddress | count | category

我有重复的ipaddress条目,我想计算每个IP的数量, 更新每个IP的计数列。

我能够这样计算重复次数

SELECT ipaddress, COUNT(*) FROM report GROUP BY ipaddress HAVING COUNT(*) > 1 ORDER BY COUNT(*) DESC 

输出

 ipaddress       COUNT(*) 
192.168.2.187        16
192.168.6.14         14
192.168.2.17         11
3192.168.3.6         9
192.168.2.77         8

我只需要用正确的计数号更新每个ip。

1 个答案:

答案 0 :(得分:1)

您可以在JOINUPDATE,如下所示:

UPDATE report r
  JOIN (SELECT ipaddress, COUNT(*) cnt FROM report GROUP BY ipaddress) up
    ON up.ipaddress = r.ipaddress
   SET r.`count` = up.cnt