mysql去除重复记录

业务上需要去除重复记录(dept_code、vehicle_type、weight一样的视为相同记录),逻辑删除,更新记录的状态为不可用(0可用,1不可用)

#1.生成回滚脚本,将以下脚本查询结果复制为insert语句并保存
SELECT
	*
FROM
	tm_full_load r
WHERE
	EXISTS (SELECT 1 FROM	(SELECT id FROM tm_full_load WHERE
					(
						dept_code,
						vehicle_type,
						weight
					) IN (
						SELECT
							t.dept_code,
							t.vehicle_type,
							weight
						FROM
							tm_full_load t
						WHERE
							t.`status` = 0
						GROUP BY
							t.dept_code,
							t.vehicle_type,
							t.weight
						HAVING
							count(*) > 1
					)
				AND id NOT IN (
					SELECT
						min(id)
					FROM
						tm_full_load
					WHERE
						`status` = 0
					GROUP BY
						dept_code,
						vehicle_type,
						weight
					HAVING
						COUNT(*) > 1
				)
				AND `status` = 0
			) a
		WHERE
			r.id = a.id
	);

#2.设置重复数据的状态不可用
DELETE
FROM
	tm_full_load
WHERE
id IN (
	SELECT
		b.id
	FROM
		(
			SELECT
				*
			FROM
				tm_full_load r
			WHERE
				EXISTS (SELECT 1 FROM	(SELECT id FROM tm_full_load WHERE
								(
									dept_code,
									vehicle_type,
									weight
								) IN (
									SELECT
										t.dept_code,
										t.vehicle_type,
										weight
									FROM
										tm_full_load t
									WHERE
										t.`status` = 0
									GROUP BY
										t.dept_code,
										t.vehicle_type,
										t.weight
									HAVING
										count(*) > 1
								)
							AND id NOT IN (
								SELECT
									min(id)
								FROM
									tm_full_load
								WHERE
									`status` = 0
								GROUP BY
									dept_code,
									vehicle_type,
									weight
								HAVING
									COUNT(*) > 1
							)
							AND `status` = 0
						) a
					WHERE
						r.id = a.id
				)
		) b
);

回滚脚本:

备份的insert脚本。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值