ALTER TABLE `qs_EventAttendee` DROP FOREIGN KEY `qs_EventAttendee_ibfk_7`; ALTER TABLE `qs_EventAttendee` ADD CONSTRAINT `qs_EventAttendee_ibfk_7` FOREIGN KEY (`cartId`) REFERENCES `quick_site`.`qs_Cart`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; CREATE TEMPORARY TABLE `tmpCart2UserMap` ( `cartId` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) NOT NULL, PRIMARY KEY (`cartId`), KEY `userId` (`userId`) ); INSERT INTO `tmpCart2UserMap` SELECT MAX(`id`), `userId` FROM `qs_Cart` WHERE `userId` > 0 AND `transactionId` IS NULL GROUP BY `userId`; -- SELECT * FROM `tmpCart2UserMap`; DELETE `c` FROM `qs_Cart` AS `c` LEFT JOIN `tmpCart2UserMap` AS `map` ON `map`.`cartId` = `c`.`id` AND `map`.`userId` = `c`.`userId` WHERE `c`.`userId` > 0 AND `transactionId` IS NULL AND `map`.`cartId` IS NULL;