我有一个包含57k条目的表格,其中包含列comp_phone(UNIQUE KEY Phone
(comp_phone
))现在我尝试使用
update uk_data set comp_phone= REPLACE(comp_phone,' ',' ')
但是因为我在这个列上有UNIQUE KEY我收到错误
[SQL] update uk_data set comp_phone= REPLACE(comp_phone,' ',' ')
[Err] 1062 - Duplicate entry '01268 203***' for key 'Phone'
所以我正在使用
DELETE FROM uk_data WHERE comp_phone = '01268 203***'
删除旧行。但这需要很长时间,因为我不知道在REPLACE之后有多少行会重复,所以有一种简单的方法来替换和删除或覆盖旧条目
THX
答案 0 :(得分:1)
测试此查询
CREATE TEMPORARY table Kratika
(
_id int,
_value varchar(50)
);
INSERT INTO Kratika
SELECT 1, '1111222255' UNION
SELECT 2, '1111222 255' UNION -- duplicate
SELECT 3, '11112222 55' UNION -- duplicate
SELECT 4, '1111222233'; -- not duplicate
SELECT * FROM Kratika;
DELETE FROM Kratika WHERE _value <> REPLACE(_value, ' ', '') ;
SELECT * FROM Kratika;
<强>输出强>
1 1111222255
2 1111222 255
3 11112222 55
4 1111222233
-- Select after deletion of duplicate records
1 1111222255
4 1111222233
<强>被修改强>
如果你对while循环没问题那么你可以测试一下(我不是MySQL开发人员,我不知道为什么MySQL不允许我写while循环,所以创建了相同的proc)
DROP PROCEDURE IF EXISTS test_kratik;
delimiter ##
CREATE PROCEDURE test_kratik
(
)
BEGIN
DROP table IF EXISTS Kratika;
CREATE TEMPORARY table Kratika
(
_id int,
_value varchar(50)
);
INSERT INTO Kratika
SELECT 1, '1111222255' UNION
SELECT 2, '1111222 255' UNION -- duplicate
SELECT 3, '11112222 55' UNION -- duplicate
SELECT 4, '1111222233'; -- not duplicate
SELECT * FROM Kratika;
SET @ID := 0;
SET @DUP_ID := 0;
SET @value := '';
WHILE @ID <= (SELECT MAX(_id) FROM kratika) DO
BEGIN
IF EXISTS(SELECT _id from kratika WHERE _id = @ID) THEN
BEGIN
SET @value = (SELECT REPLACE(_value, ' ', '') from kratika WHERE _id = @ID);
DELETE FROM kratika
WHERE REPLACE(_value, ' ', '') = @value
AND _id <> @ID;
END;
END IF;
SET @ID = @ID + 1;
END;
END WHILE;
UPDATE kratika
SET _value = REPLACE(_value, ' ', '')
WHERE _value <> REPLACE(_value, ' ', '') ;
SELECT * FROM kratika;
END ##
delimiter ;
CALL test_kratik();
已更新 如果您不想使用while循环,那就没关系....
DROP TABLE IF EXISTS Kratika;
CREATE TEMPORARY table Kratika
(
_id int,
_value varchar(50)
);
INSERT INTO Kratika
SELECT 1, '1111222255' UNION
SELECT 2, '1111222 255' UNION -- duplicate
SELECT 3, '11112222 55' UNION -- duplicate
SELECT 4, '111122 2233'; -- not duplicate
DROP TABLE IF EXISTS copy_temp;
CREATE TEMPORARY table copy_temp
(
_id1 int,
_value1 varchar(50)
);
INSERT INTO copy_temp
SELECT _id, _value FROM kratika;
SELECT * FROM Kratika;
DELETE FROM Kratika
WHERE _id <> (SELECT _id1 FROM copy_temp
WHERE REPLACE(_value, ' ', '') = REPLACE(_value1, ' ', '')
Limit 1
);
UPDATE kratika
SET _value = REPLACE(_value, ' ', '')
WHERE _value <> REPLACE(_value, ' ', '') ;
SELECT * FROM Kratika;
<强>输出强>
1 1111222255
2 1111222 255
3 11112222 55
4 1111222233
更新后
1 1111222255
4 1111222233