码迷,mamicode.com
首页 > 数据库 > 详细

查询数据库中的重复数据——MySQL数据库

时间:2021-06-16 17:52:07      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:参考   innodb   bsp   htm   post   str   utf8mb4   插入数据   数据   

 

1、建表语句

DROP TABLE IF EXISTS `t_people`;
CREATE TABLE `t_people`  (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `people_no` varchar(18) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
  `people_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

2、插入数据

INSERT INTO `t_people` VALUES (1, ‘100‘, ‘张三‘);
INSERT INTO `t_people` VALUES (2, ‘100‘, ‘张三‘);
INSERT INTO `t_people` VALUES (3, ‘100‘, ‘张三‘);
INSERT INTO `t_people` VALUES (4, ‘101‘, ‘李四‘);
INSERT INTO `t_people` VALUES (5, ‘101‘, ‘李四‘);
INSERT INTO `t_people` VALUES (6, ‘102‘, ‘王五‘);
INSERT INTO `t_people` VALUES (7, ‘103‘, ‘赵六‘);
INSERT INTO `t_people` VALUES (8, ‘104‘, ‘田七‘);
INSERT INTO `t_people` VALUES (9, ‘100‘, ‘嘻嘻‘);
INSERT INTO `t_people` VALUES (10, ‘100‘, ‘小粉丝‘);

技术图片

3、查询 people_no 重复的记录

SELECT * 
FROM t_people 
WHERE people_no IN (
	SELECT people_no FROM t_people GROUP BY people_no HAVING COUNT(people_no) > 1
);

技术图片

4、查询 people_no 重复且不包含 id 最小的记录

SELECT * 
FROM t_people 
WHERE people_no IN (
	SELECT people_no FROM t_people GROUP BY people_no HAVING COUNT(people_no) > 1
) AND id NOT IN (
	SELECT MIN(id) FROM t_people GROUP BY people_no HAVING COUNT(people_no) > 1
);

技术图片

5、查询 people_no 和 people_name 重复的记录

SELECT * 
FROM t_people 
WHERE (people_no, people_name) IN (
	SELECT people_no, people_name FROM t_people GROUP BY people_no, people_name HAVING COUNT(*) > 1
);

技术图片

6、查询 people_no 和 people_name 重复且不包含 id 最小的记录

SELECT * 
FROM t_people 
WHERE (people_no, people_name) IN (
	SELECT people_no, people_name FROM t_people GROUP BY people_no, people_name HAVING COUNT(*) > 1 
) AND id NOT IN (
	SELECT MIN(id) FROM t_people GROUP BY people_no, people_name HAVING COUNT(*) > 1
);

技术图片

本文参考:https://www.cnblogs.com/LDDXFS/p/9867928.html

查询数据库中的重复数据——MySQL数据库

标签:参考   innodb   bsp   htm   post   str   utf8mb4   插入数据   数据   

原文地址:https://www.cnblogs.com/xianz666/p/14887632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!