Skip to content

Instantly share code, notes, and snippets.

@barretts
Last active August 18, 2020 19:29
Show Gist options
  • Save barretts/b1a8c2d4865557611df550bd8695ca7c to your computer and use it in GitHub Desktop.
Save barretts/b1a8c2d4865557611df550bd8695ca7c to your computer and use it in GitHub Desktop.
mysql fetch loop rows delete duplicates without primary keys
DELIMITER ;;
DROP PROCEDURE IF EXISTS Delete_roletouser_Duplicates;;
CREATE PROCEDURE Delete_roletouser_Duplicates()
BEGIN
DECLARE lmt INT DEFAULT 0;
DECLARE done INT DEFAULT 0;
DECLARE _role_id CHAR(36);
DECLARE _user_id CHAR(36);
DECLARE _duplicate_count INT;
DECLARE curRoletouser CURSOR FOR
SELECT role_id, user_id, COUNT(*)
FROM roletouser
GROUP BY role_id, user_id
HAVING COUNT(*) > 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN curRoletouser;
getRoletouser: LOOP FETCH curRoletouser INTO _role_id, _user_id, _duplicate_count;
IF done THEN
LEAVE getRoletouser;
END IF;
SET lmt = _duplicate_count - 1;
IF lmt > 0 THEN
DELETE FROM roletouser WHERE role_id = _role_id AND user_id = _user_id LIMIT lmt;
END IF;
ITERATE getRoletouser;
END LOOP getRoletouser;
CLOSE curRoletouser;
END;;
DELIMITER ;
CALL Delete_roletouser_Duplicates();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment