合并重复的电子邮件和点mysql

时间:2013-08-29 05:31:45

标签: mysql sql

我有一个MySQL表,它有三列:

Userid         | Email               | Points
---------------------------------------------------------
1              | jdoe@company.com    | 20
2              | jdoe%40company.com  | 25
3              | rwhite@company.com  | 14
4              | rwhite%40company.com| 10

我想要做的是删除重复的电子邮件和合并点。我希望我的桌子看起来像这样:

Userid         | Email               | Points
---------------------------------------------------------
1              | jdoe@company.com    | 45
3              | rwhite@company.com  | 24

我的查询如何返回我的欲望表?

任何人都知道如何做到这一点?

提前致谢!

2 个答案:

答案 0 :(得分:2)

你在找这样的东西吗?

SELECT MIN(userid) userid, email, SUM(points) points
  FROM 
(
  SELECT userid, REPLACE(email, '%40', '@') email, points
    FROM table1
) q
  GROUP BY email

输出:

| USERID |              EMAIL | POINTS |
|--------|--------------------|--------|
|      1 |   jdoe@company.com |     45 |
|      3 | rwhite@company.com |     24 |

这是 SQLFiddle 演示


现在,如果您想要就地重复删除表格,可以执行

-- Fix emails
UPDATE table1
   SET email = REPLACE(email, '%40', '@')
 WHERE email LIKE '%\%40%';
-- Merge points for duplicate records
UPDATE table1 t JOIN
(
  SELECT email, SUM(points) points
    FROM table1
   GROUP BY email
  HAVING COUNT(*) > 1
) q ON t.email = q.email
   SET t.points = q.points;
-- Delete all duplicate records except ones with lowest `userid`
DELETE t 
  FROM table1 t JOIN
(
  SELECT MIN(userid) userid, email
    FROM table1
   GROUP BY email
  HAVING COUNT(*) > 1
) q ON t.email = q.email
 WHERE t.userid <> q.userid;

这是 SQLFiddle 演示

答案 1 :(得分:0)

使用此查询,假设您希望按原样匹配电子邮件而不进行任何修改

SELECT MIN(user_id), SUM(points)as points, email FROM table_name GROUP BY email