MySQL更新冲突行以使其唯一

时间:2014-03-03 19:21:59

标签: mysql sql

我有一个mysql InnoDB表,其中包含一百万行,其索引列没有唯一性约束。我希望将冲突的行标记为存在冲突,然后将唯一性约束添加到该列。这些行的所有者将在线下修复它们。这是我的代码:

UPDATE users u SET fid = concat("@conflict_", fid, "_", RAND())
WHERE u.fid IN (SELECT fid from (
    SELECT fid
    FROM users
    WHERE fid IS NOT NULL
    GROUP BY fid
    HAVING COUNT(fid) > 1) 
AS TmpUsers);

以上查询非常慢。更新需要几个小时。什么是加快它的好方法?

更新

永远不要使用子查询来更新包含大量记录的表。在post 14431772找到了一个示例联接:

UPDATE  users u 
    INNER JOIN
    (
        SELECT  fid
        FROM    users
        where fid IS NOT NULL
        GROUP   BY fid
        HAVING  COUNT(*) > 1
    ) b ON u.fid = b.fid
SET u.fid = concat("@conflict_", u.fid, "_", RAND());

谢谢@Powerlord。

1 个答案:

答案 0 :(得分:0)

试试这样的事情:

create temporary table myCustomTable as (
SELECT fid
FROM users
WHERE fid IS NOT NULL
GROUP BY fid
HAVING COUNT(fid) > 1);

UPDATE users u SET u.fid = concat("@conflict_", u.fid, "_", RAND())
WHERE u.fid IN (select mc.fid from myCustomTable mc);