Created
August 8, 2013 09:23
-
-
Save weareoutman/6183117 to your computer and use it in GitHub Desktop.
mysql 将一个表的重复数据合并
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- 临时表 t_temp_a,有重复articleid的记录 | |
| CREATE TEMPORARY TABLE t_temp_a ( | |
| SELECT d.id, d.articleid, d.hitcount, d.cnt | |
| FROM ( | |
| SELECT c.id, c.articleid, c.hitcount, b.cnt | |
| FROM t_article_hitcount AS c | |
| INNER JOIN ( | |
| SELECT articleid, cnt | |
| FROM ( | |
| SELECT articleid, COUNT(*) AS cnt | |
| FROM t_article_hitcount | |
| GROUP BY articleid | |
| ) AS a | |
| WHERE cnt >= 2 | |
| ) AS b ON b.articleid = c.articleid | |
| ) d | |
| ORDER BY d.articleid ASC | |
| ); | |
| -- 将 重复articleid 的记录的 hitcount 合并 | |
| UPDATE t_article_hitcount AS a | |
| INNER JOIN ( | |
| SELECT id, articleid, SUM(hitcount) AS hitcount, cnt | |
| FROM t_temp_a | |
| GROUP BY articleid | |
| ) AS b ON a.articleid = b.articleid | |
| SET a.hitcount = b.hitcount; | |
| -- 对于重复数据,保留且仅保留一条 | |
| DELETE | |
| FROM t_article_hitcount | |
| WHERE id IN ( | |
| SELECT id | |
| FROM t_temp_a | |
| ) AND id NOT IN ( | |
| SELECT MIN(id) | |
| FROM t_temp_a | |
| GROUP BY articleid | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment