MYSQL 刪除商品主圖重複數據,只保留一條

-- 刪除重複數據,只保留一條
當一個數據表中,存在重複的數據,若是重複多條,能夠把重複的數據都查出來,而後取最大的ID,根據條件刪除ID並非最大的便可,SQL腳本以下sql

DELETE
FROM
	t_pd_picture
WHERE
	ID IN (
		SELECT
			ID
		FROM
			(
				SELECT
					ID
				FROM
					t_pd_picture
				WHERE
					product_id IN (
						SELECT
							product_id
						FROM
							`t_pd_picture` t
						WHERE
							t.picture_pd_type = 0
						GROUP BY
							product_id,
							picture_pd_type
						HAVING
							COUNT(product_id) > 1
					)
				AND picture_pd_type = 0
				AND ID NOT IN (
					SELECT
						MIN(ID)
					FROM
						`t_pd_picture` t
					WHERE
						t.picture_pd_type = 0
					GROUP BY
						product_id,
						picture_pd_type
					HAVING
						COUNT(product_id) > 1
				)
			) AS TEMP_TABLE
	);
相關文章
相關標籤/搜索