使用 NOT IN 排除其他记录来通过特定条件查找重复项中的单个值的 MySQL 查询


首先,我们创建一个表 -

mysql> create table DemoTable
(
   Id int,
   FirstName varchar(100)
);
Query OK, 0 rows affected (0.69 sec)

使用 insert 命令在表中 插入一些记录 -

mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(100,'Robert');
Query OK, 1 row affected (0.48 sec)
mysql> insert into DemoTable values(100,'Mike');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(100,'Sam');
Query OK, 1 row affected (0.48 sec)
mysql> insert into DemoTable values(101,'David');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(101,'Robert');
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable values(210,'Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(210,'Bob');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(210,'Sam');
Query OK, 1 row affected (0.17 sec)

使用 select 语句从表中显示所有记录 -

mysql> select *from DemoTable;

这将生成以下输出 -

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  100 | Chris     |
|  100 | Robert    |
|  100 | Mike      |
|  100 | Sam       |
|  101 | David     |
|  101 | Robert    |
|  210 | Chris     |
|  210 | Bob       |
|  210 | Sam       |
+------+-----------+
9 rows in set (0.00 sec)

以下查询可找到具有特定条件的重复项中的单个值 -

mysql> select distinct Id from DemoTable
where Id not in
(
   select Id from DemoTable where FirstName='Chris'
);

这将生成以下输出 -

+------+
| Id   |
+------+
| 101  |
+------+
1 row in set (0.08 sec)

更新于: 2019 年 9 月 26 日

66 次查看

启动您的 职业

通过完成课程获得认证

开始学习
广告