我有一个名为Positions的表,其中包含以下数据:
Id PositionId
1 'a'
2 'a '
3 'b '
4 'b'
其中一些有空格,所以我的想法是删除那些空格,这不是实际表只是一个具有更多数据的表的示例。 所以我创建了迭代PositionIds的程序并比较它们,如果它们匹配,则删除其中一个:
CREATE PROCEDURE remove_double_positions()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE current VARCHAR(255);
DECLARE previous VARCHAR(255) DEFAULT NULL;
DECLARE positionCur CURSOR FOR SELECT PositionId FROM Positions ORDER BY PositionId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN positionCur;
clean_duplicates: LOOP
FETCH positionCur INTO current;
IF done THEN
LEAVE clean_duplicates;
END IF;
IF previous LIKE current THEN
DELETE FROM Positions WHERE PositionId = current;
END IF;
SET previous = current;
END LOOP clean_duplicates;
CLOSE positionCur;
END
出于某种原因,它显示2行受到影响,但实际上删除了所有4行,我不知道原因,你能帮帮我吗。
答案 0 :(得分:0)
没有游标和程序的其他解决方案。我在ORACLE上查了一下。希望它有所帮助。
DELETE FROM positions
WHERE id IN ( SELECT t1.id
FROM positions t1,
positions t2
WHERE t1.positionId = TRIM(t2.positionId)
AND t1.positionId != t2.positionId
);
<强>更新强>
mysql正在发生一些糟糕的事情。在强大的结尾处出现空白的一些问题和此错误1093错误。
现在使用MySQL 5.5.9检查我的解决方案
CREATE TABLE positions (
id INT NOT NULL,
positionid VARCHAR(2) NOT NULL
);
INSERT INTO positions VALUES
( 1, 'a'),
( 2, 'a '),
( 3, 'b'),
( 4, 'b ');
DELETE FROM positions
WHERE id IN ( SELECT t3.id FROM
(SELECT t2.id
FROM positions t1,
positions t2
WHERE t1.positionid = t2.positionid
AND LENGTH(t1.positionid) = 1
AND length(t2.positionid) = 2
) t3
);
mysql> SELECT * from positions;
+----+------------+
| id | positionid |
+----+------------+
| 1 | a |
| 3 | b |
+----+------------+
2 rows in set (0.00 sec)
mysql>
这&#34; double&#34;从删除SQL将修复此错误1093
希望这有帮助。
答案 1 :(得分:0)
从类似运算符下的手册https://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html#operator_like - 按照SQL标准,LIKE在每个字符的基础上执行匹配,因此它可以产生与=比较运算符不同的结果:...特别是尾随空格是重要的,对于使用=运算符执行的CHAR或VARCHAR比较不是这样:
mysql> SELECT 'a' = 'a ', 'a' LIKE 'a ';
+------------+---------------+
| 'a' = 'a ' | 'a' LIKE 'a ' |
+------------+---------------+
| 1 | 0 |
+------------+---------------+
1 row in set (0.00 sec)
如果将删除位修改为
,您的程序将按预期工作 IF trim(previous) = trim(current) THEN
DELETE FROM Positions WHERE PositionId like current;
END IF;