Mysql語句查詢指定重複記錄和刪除重複記錄僅保留一條【親測可以】

FeelTouch發表於2018-06-05

對於髒資料,除了通過程式來修復,也可以通過mysql本身來修復。

問題一:查詢指定組合欄位的重複記錄

SELECT
	*
FROM
	tb_teacher a
WHERE
	(a.user_id, a.create_time) IN (
		SELECT
			user_id,
			create_time
		FROM
			tb_teacher
		WHERE
			type = 3
		GROUP BY
			user_id,
			create_time
		HAVING
			count(*) > 3
	)
AND a.id NOT IN (
	SELECT
		min(id)
	FROM
		tb_teacher
	GROUP BY
		user_id,
		create_time
	HAVING
		count(*) > 1
);

點評:select的組合查詢比較常規,可以通過表別名來識別子表。刪除的就更為複雜。

問題二:刪除指定組合欄位的重複記錄並僅保留一條最小ID記錄

DELETE
FROM
	tb_teacher
WHERE
	(user_id, create_time) IN (
		SELECT
			*
		FROM
			(
				SELECT
					user_id,
					create_time
				FROM
					tb_teacher
				WHERE
					type = 3
				GROUP BY
					user_id,
					create_time
				HAVING
					count(*) > 3
			) b
	)
AND id NOT IN (
	SELECT
		*
	FROM
		(
			SELECT
				min(id)
			FROM
				tb_teacher
			GROUP BY
				user_id,
				create_time
			HAVING
				count(*) > 1
		) c
);

點評:相對select,delete 表現得更為苛刻,具體表現和解決方法如下:


1.使用mysql進行delete from操作時,若子查詢的 FROM 字句和更新/刪除物件使用同一張表,會出現錯誤。

mysql> DELETE FROM tab1 WHERE col1 = ( SELECT MAX( col1 ) FROM tab1 );
ERROR 1093 (HY000): You can’t specify target table ‘tab1′ for update in FROM clause

針對“同一張表”這個限制,撇開效率不談,多數情況下都可以通過多加一層select 別名表來變通解決,像這樣

DELETE FROM tab1
WHERE col1 = (
SELECT MAX( col1 )
FROM (
SELECT * FROM tab1
) AS t
);

------------------------------------------------------------------------

2. mysql delete from where in 時後面 的查詢語句裡不能加where條件

Sql程式碼 
      delete from `t_goods` where fi_id in (select * from ( select fi_id from `t_goods` where fs_num is null and fs_name is null and fs_type is null and fs_using is null and fs_lifetime is null) b)  

Sql程式碼 
      delete from `t_goods` where fi_id in (select fi_id from `t_goods` where fs_num is null and fs_name is null and fs_type is null and fs_using is null and fs_lifetime is null)   

Sql程式碼 
      delete from `t_goods` where fi_id in ( select fi_id from `t_goods` )   

上面三種情況,只有中間的不能執行。

綜合起來就是mysql delete from where in 時後面 的查詢語句裡不能加where條件

---------------------------------------------------------------------------

3. delete from table... 這其中table不能使用別名

Sql程式碼 

    delete from student a where a.id in (1,2);(執行失敗)

    select a.* from student a where a.id in (1,2);(執行成功)
參考:https://blog.csdn.net/tjcyjd/article/details/8950621

相關文章