简体   繁体   中英

Update table with join to self and sub-select

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

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM