MySQL的,删除重复和SUM在另一个表

时间:2019-12-18 03:02:01

标签: mysql

我有一个包含重复数据的客户表,例如:一个电话为1234的客户多次在同一个商店中。

我尝试使用以下代码在同一商店中使用同一部电话获取所有重复的客户端:

SELECT 
    GROUP_CONCAT(DISTINCT id
        SEPARATOR ',') AS ids
FROM
    clients
GROUP BY phone , store_id
HAVING COUNT(phone) > 1

表格:

CLIENTS
id    phone   store_id
------------------------
1     1234       3
2     1234       3
3     4321       4
4     4321       4
5     4321       4

USER_POINTS
id   client_id     points
------------------------
1       1            10
2       2            5
3       3            2
4       4            9
5       5            1

如何在将重复的客户点累加到单个客户点表行的同时从客户表中删除重复的客户,并用-1更新其余客户? 我尝试了以下操作,但没有得到想要的结果。

UPDATE user_points AS up,
    (SELECT 
        client_id,
            MIN(id) AS min_id,
            SUM(points) AS sum_points
    FROM
        user_points
    WHERE
        client_id IN (SELECT id FROM clients GROUP BY phone, store_id HAVING COUNT(phone) > 1)) AS p 
SET 
    up.points = CASE
        WHEN up.id = p.min_id THEN p.sum_points
        ELSE -1
    END;

我想要类似的东西

USER_POINTS
id   client_id     points
------------------------
1       1            15
2       2            -1
3       3            12
4       4            -1
5       5            -1

1 个答案:

答案 0 :(得分:2)

您需要对LEFT JOIN进行user_points到派生的客户点和最小客户ID值之和的表中,然后在{{1 }}的值是points

min_id

输出:

NOT NULL

dbfiddle上的演示(略有扩展,以包括电话UPDATE user_points u LEFT JOIN (SELECT MIN(c.id) AS min_id, SUM(points) AS sum_points FROM clients c JOIN user_points u ON u.client_id = c.id GROUP BY phone, store_id) c ON u.client_id = c.min_id SET u.points = CASE WHEN c.min_id IS NOT NULL THEN c.sum_points ELSE -1 END 的其他商店)。