测试这个查询
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