我有一个包含重复行的表。我想在删除之前更新行,只是为了确保删除好的行。
删除查询是这样的,有效:
DELETE FROM cscart_products
WHERE updated_timestamp
NOT IN (SELECT *
FROM (SELECT MAX(n.updated_timestamp)
FROM cscart_products n
GROUP BY n.product_code) x)
示例表:
product_code product_type status updated_timestamp
DUSP1893 P A 1551
DUSP1893 P A 322
AH324444 P A 555
AH324444 P A 21332
某些产品具有相同的product_code。我想更新那些具有较小的updated_timestamp的状态从状态A到H.
谢谢你
答案 0 :(得分:0)
您必须在交易中执行此操作。 1.开始交易 2.更新 3.删除 4.提交交易
START TRANSACTION;
UPDATE cscart_products SET status="H" WHERE updated_timestamp<some_value AND product_code IN (code1,code2,....codeN);
DELETE FROM cscart_products WHERE status="H" AND product_code IN (code1,code2,....codeN);
COMMIT;
答案 1 :(得分:0)
首先获取时间戳较小的行,然后更新这些记录,如下所示:
UPDATE cscart_products
INNER JOIN (
SELECT product_code pc, MIX(updated_timestamp) ts
FROM cscart_products
GROUP BY product_code
) t
ON cscart_products.product_code = t.pc
AND cscart_products.updated_timestamp = t.ts
SET status = 'H'
内部查询将为您提供具有较小时间戳的product_code行。
答案 2 :(得分:0)
它不应该比这更复杂:
-- mark the rows for which the updated_timestamp is smaller
-- than the maximum timestamp for that product_code
UPDATE cscart_products
SET status = 'H'
WHERE updated_timestamp
NOT IN (SELECT *
FROM (SELECT MAX(n.updated_timestamp)
FROM cscart_products n
GROUP BY n.product_code) x);
-- delete the marked rows (or don't, whatever you feel like)
DELETE FROM cscart_products
WHERE status = 'H';
答案 3 :(得分:0)
更新product_code中重复的最小updated_timestamp,状态为“H”
UPDATE cscart_products SET status='H'
WHERE updated_timestamp IN
(SELECT * FROM(SELECT MIN(updated_timestamp) FROM cscart_products
GROUP BY product_code HAVING COUNT(product_code)>1) X);