---
title: "删除数据库中多字段重复的数据"
author: "javafan_303"
date: "2016-10-12T19:59:55Z"
tags: []
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2016-10-12T19:58:06Z"
id: 2330186
url: "https://cailin.iteye.com/blog/2330186"
---

```
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
)
```

   通过上面语句能找出来数据库中stu\_id,tea\_id字段重复的数据，如果数据库中有3条重复的数据，这里将筛    选出来2条重复的数据，数据库中保留了一条最小id的数据。

   表结构事例如下

```
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 '添加时间',
  PRIMARY KEY (`id`),
  KEY `tea_id` (`tea_id`),
  KEY ` stu_id` (`stu_id`)
)
```