我正在尝试基于两列向表添加唯一约束。在表中,我目前有两个不唯一的实例。 (意思是我有4行打破了唯一约束)。
我希望在每种情况下更新“较旧”的行,其中较旧的是较低的ID。这是我到目前为止所得到的:
查询:
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)
但我收到错误:
Error Code: 1052 Column 'deleted_at' in field list is ambiguous
。
我尝试将设置部分更改为:
SET p1.deleted_at = NOW(), p1.`code` = CONCAT(p1.`code`, p1.id)
然后我得到Error Code: 1093 You can't specify target table 'p1' for update in FROM clause
答案 0 :(得分:1)
通过为子查询提供新别名来尝试此操作
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
)