删除重复数据的mysql

时间:2018-10-02 07:01:51

标签: mysql sql

如果使用,我们有重复的ID

SELECT MAX(id), COUNT(id) AS count 
FROM user_status 
GROUP BY user_id, user_type 
HAVING COUNT(*) > 1

我们得到了重复的数据

现在,当我尝试通过

将其插入删除时
DELETE 
FROM user_status 
WHERE id IN (SELECT MAX(id), COUNT(id) AS count 
             FROM user_status 
             GROUP BY user_id, user_type 
             HAVING COUNT(*) > 1
            )

我遇到以下错误

Operand should contain 1 column

我该如何解决? TIA

2 个答案:

答案 0 :(得分:1)

很明显,您正在选择subquery子句中不允许的IN中的两列,但mysql仍然在查询中显示一些错误,因此请替换用如下所示的连接查询

DELETE us 
FROM user_status us
INNER JOIN (SELECT MAX(id) id 
            FROM user_status 
            GROUP BY user_id, user_type HAVING COUNT(*) > 1) t ON t.id = us.id

答案 1 :(得分:1)

怎么样

DELETE user_status
FROM user_status LEFT JOIN (
    SELECT MAX(user_id) maxId
    FROM user_status
    GROUP BY user_type
) a ON maxId = user_id
WHERE maxId IS NULL;

在您的代码where col1 in (select col1, col2)中,列数根本不匹配。如果您引用每个选定的列,则其原理是:

DELETE FROM user_status
WHERE (user_id, user_type) NOT IN (
    SELECT MAX(user_id) maxId, user_type
    FROM (select * from user_status) a
GROUP BY user_type);