sku對應的重量表,應該一個sku_id 對應唯一 一條重量資料,由於程式錯誤導致出現一樣的冗餘資料。只保留一條,其他的刪除。
欄位 | 說明 |
---|---|
id | 自增 |
sku_id | sku_id標識 |
weight | 重量 |
假設表名:weight
查詢有重複資料的列表
SELECT sku_id,COUNT(id) FROM weight GROUP BY sku_id HAVING COUNT(sku_id) > 1
查詢重複資料裡面每個最小的id
SELECT min(id) FROM weight GROUP BY sku_id HAVING COUNT(sku_id) > 1
查詢去掉重複資料最小id的其他資料
SELECT id,sku_id FROM weight WHERE sku_id IN(
SELECT sku_id FROM weight GROUP BY sku_id HAVING COUNT(sku_id) > 1
)
AND id NOT IN(
SELECT MIN(id) FROM weight GROUP BY sku_id HAVING COUNT(sku_id) > 1
)
刪除去掉重複資料最小id的其他資料
DELETE FROM weight WHERE sku_id IN(
SELECT sku_id FROM weight GROUP BY sku_id HAVING COUNT(sku_id) > 1
)
AND id NOT IN(
SELECT MIN(id) FROM weight GROUP BY sku_id HAVING COUNT(sku_id) > 1
)
原因是:刪除這個表的同時又查詢了這個表,查詢這個表的同時又去刪除了這個表,可以理解為死鎖。mysql不支援這種刪除查詢同一張表的操作
錯誤程式碼: 1093
You can't specify target table 'weight' for update in FROM clause
解決辦法如下:把要刪除的資料查詢出來做為一個第三方表,然後篩選刪除。
DELETE FROM `weight` WHERE sku_id IN(
SELECT sku_id FROM (SELECT sku_id FROM `weight` GROUP BY sku_id HAVING COUNT(sku_id) > 1) table1
)
AND id NOT IN (
SELECT id FROM (SELECT MIN(id) AS id FROM `weight` GROUP BY sku_id HAVING COUNT(sku_id) > 1) table2
)
更新也和上面操作原理相同。| | |
| ———— | ———— |
| | |
| | |
本作品採用《CC 協議》,轉載必須註明作者和本文連結