在 MySQL 中查找所有具有唯一姓氏的用户?
若要查找具有唯一姓氏的所有用户,请使用 GROUP BY HAVING COUNT()。
让我们创建一个表格 -
示例
mysql> create table demo76 -> ( -> firstName varchar(20), -> lastName varchar(20) -> ); Query OK, 0 rows affected (9.29
在表中插入一些记录,借助于 insert 命令 -
示例
mysql> insert into demo76 values('John','Doe'); Query OK, 1 row affected (2.52 mysql> insert into demo76 values('David','Smith'); Query OK, 1 row affected (6.31 mysql> insert into demo76 values('Adam','Smith'); Query OK, 1 row affected (1.52
使用 select 语句显示表中的记录 -
示例
mysql> select *from demo76;
这将产生以下输出 -
输出
+-----------+----------+
| firstName | lastName |+-----------+----------+
| John | Doe || David | Smith |
| Adam | Smith |+-----------+----------+
3 rows in set (0.00 sec)
以下是查询具有唯一姓氏的所有用户的方法 -
示例
mysql> select max(tbl.firstName), tbl.lastName, -> count(distinct tbl.firstName) as CountOfFirstName -> from demo76 as tbl -> group by tbl.lastName -> having count(distinct tbl.firstName) = 1;
这将产生以下输出 -
输出
+--------------------+----------+------------------+
| max(tbl.firstName) | lastName | CountOfFirstName |+--------------------+----------+------------------+
| John | Doe | 1 |+--------------------+----------+------------------+
1 row in set (0.00 sec)
广告