通过 NOT IN 实现 MySQL 条件 GROUP BY 以从重复列值中筛选记录
我们首先创建一个表 −
mysql> create table DemoTable ( Name varchar(40), Score int ); Query OK, 0 rows affected (0.48 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('Adam',89); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Adam',89); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris',89); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Chris',89); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Bob',98); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Bob',89); Query OK, 1 row affected (0.16 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable;
这将生成以下输出 −
+-------+-------+ | Name | Score | +-------+-------+ | Adam | 89 | | Adam | 89 | | Chris | 89 | | Chris | 89 | | Bob | 98 | | Bob | 89 | +-------+-------+ 6 rows in set (0.00 sec)
以下是使用 NOT IN() 实现条件 GROUP BY 的查询 −
mysql> select distinct Name from DemoTable where Name not in(select Name from DemoTable where Score <> 89);
这将生成以下输出 −
+-------+ | Name | +-------+ | Adam | | Chris | +-------+q 2 rows in set (0.06 sec)
广告