Delete duplicate data in multiple fields in database

SELECT
	id
FROM
	tablename a
WHERE
	(a.stu_id, a.tea_id) IN (
		SELECT
			stu_id,
			tea_id
		FROM
			tablename
		GROUP BY
			stu_id,
			tea_id
		HAVING
			count(*) > 1
	)
AND id NOT IN (
	SELECT
		min(id)
	FROM
		tablename
	GROUP BY
		stu_id,
		tea_id
	HAVING
		count(*) > 1
)

   The above statement can find out the duplicate data in the stu_id and tea_id fields in the database. If there are 3 duplicate data in the database, 2 duplicate data will be filtered out here, and the data with the smallest id will be retained in the database.

   Examples of table structure are as follows

CREATE TABLE `tablename` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `stu_id` bigint(20) NOT NULL DEFAULT '0',
  `tea_id` bigint(20) NOT NULL DEFAULT '0',
  `add_time` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Add time',
  PRIMARY KEY (`id`),
  KEY `tea_id` (`tea_id`),
  KEY ` stu_id` (`stu_id`)
)

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326682140&siteId=291194637