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 `mm_Cart` WHERE `userId` > 0 AND `transactionId` IS NULL GROUP BY `userId`; SELECT * FROM `tmpCart2UserMap`; DELETE `c` FROM `mm_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;