如果行重复,MySQL更新
我有一张有重复行的桌子。我想在删除行之前更新它们,只是为了确保删除好的行 删除查询如下所示,并且可以工作:如果行重复,MySQL更新,mysql,Mysql,我有一张有重复行的桌子。我想在删除行之前更新它们,只是为了确保删除好的行 删除查询如下所示,并且可以工作: 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
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
某些产品具有相同的产品代码。我想用更小的更新时间戳从状态a更新到状态H
谢谢您必须在交易时这样做。 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;
启动事务;
UPDATE cscart_products SET status=“H”其中updated_timestamp首先获取时间戳较小的行,然后更新这些记录,如下所示:
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'
内部查询将为您提供具有较小时间戳的产品代码行。应该不会比这更复杂:
-- 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';
更新产品代码中重复的最小更新时间戳,状态为“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);
这篇文章读了三遍,仍然没有弄清楚真正的问题是什么。您只想在状态上添加一个额外的条件?例如,我想在DUSP1893将状态从A更改为H,其中更新的时间戳更小。AH324444也一样。为什么OP必须在事务中执行此操作?