要查找所有具有唯一姓氏的用户,请使用GROUP BY HAVING COUNT()
。
让我们创建一个表-
mysql> create table demo76
-> (
-> firstName varchar(20),
-> lastName varchar(20)
-> );
以下是查找所有具有唯一姓氏的用户的查询-
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)