MySQL 查询如何避免显示重复值?
mysqlmysqli database
为此,您可以使用 GROUP BY 并使用 COUNT 来仅获取非重复值。以下是语法 −
select yourColumnName from yourTableName group by yourColumnName having count(*)=1;
首先我们创建一个表 −
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Subject varchar(100) -> ); Query OK, 0 rows affected (0.70 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(Subject) values('MySQL'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable(Subject) values('MongoDB'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Subject) values('Java'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Subject) values('MongoDB'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Subject) values('C'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Subject) values('C++'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Subject) values('Java'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Subject) values('C'); Query OK, 1 row affected (0.23 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
+----+---------+ | Id | Subject | +----+---------+ | 1 | MySQL | | 2 | MongoDB | | 3 | Java | | 4 | MongoDB | | 5 | C | | 6 | C++ | | 7 | Java | | 8 | C | +----+---------+ 8 rows in set (0.00 sec)
以下是避免显示重复的查询 −
mysql> select Subject from DemoTable group by Subject having count(*)=1;
输出
+---------+ | Subject | +---------+ | MySQL | | C++ | +---------+ 2 rows in set (0.00 sec)