Reputation: 7005
I am trying to add a unique constraint to a table based on two columns. In the table I currently have two instances which are not unique. (Meaning I have 4 rows which break the unique constraint).
I want to update the "older" rows in each of these cases, where older is the lower id. This is what I've got so far:
Query:
UPDATE `promo` p1
INNER JOIN promo p2
ON p2.code = p1.code
SET deleted_at = NOW(), `code` = CONCAT(p1.`code`, p1.id)
WHERE p1.id < p2.id
AND p1.`code` IN
(SELECT `code` FROM promo GROUP BY `code`, deleted_at HAVING COUNT(id) > 1)
But I get the error:
Error Code: 1052 Column 'deleted_at' in field list is ambiguous
.
I tried changing the set part to:
SET p1.deleted_at = NOW(), p1.`code` = CONCAT(p1.`code`, p1.id)
but then I get Error Code: 1093 You can't specify target table 'p1' for update in FROM clause
Fiddle: http://sqlfiddle.com/#!2/16cc1/1/0
Upvotes: 1
Views: 78
Reputation: 64486
Try this by giving the new alias to your subquery
UPDATE `promo` p1
INNER JOIN promo p2
ON p2.code = p1.code
SET p1.deleted_at = NOW(), p1.`code` = CONCAT(p1.`code`, p1.id)
WHERE p1.id < p2.id
AND p1.`code` IN
(SELECT t.`code` FROM
(SELECT `code` FROM promo GROUP BY `code`, deleted_at HAVING COUNT(id) > 1) t
)
Upvotes: 1