方便演示,我们创建一个名为contacts
表,其中包含四个列:id
,first_name
,last_name
和email
。
表中数据如下
| id | first_name | last_name | email | +----+------------+-----------------+--------------------------------+ | 1 | Carine | Schmitt | [email protected] | | 2 | Jean | King | [email protected] | | 3 | Peter | Ferguson | [email protected] | | 4 | Janine | Labrune | [email protected] | | 5 | Jonas | Bergulfsen | [email protected] | | 6 | Janine | Labrune | [email protected] | | 7 | Susan | Nelson | [email protected] | | 8 | Zbyszek | Piestrzeniewicz | [email protected] | | 9 | Roland | Keitel | [email protected] | | 10 | Julie | Murphy | [email protected] | | 11 | Kwai | Lee | [email protected] | | 12 | Jean | King | [email protected] | | 13 | Susan | Nelson | [email protected] | | 14 | Roland | Keitel | [email protected]
在一列中找到重复的值
1 SELECT 2 email, 3 COUNT(email) 4 FROM 5 contacts 6 GROUP BY email 7 HAVING COUNT(email) > 1;
输出如下
+-------------------------+--------------+ | email | COUNT(email) | +-------------------------+--------------+ | [email protected] | 2 | | [email protected] | 2 | +-------------------------+--------------+ 2 rows in set
在多个列中查找重复值
1 SELECT 2 first_name, COUNT(first_name), 3 last_name, COUNT(last_name), 4 email, COUNT(email) 5 FROM 6 contacts 7 GROUP BY 8 first_name , 9 last_name , 10 email 11 HAVING COUNT(first_name) > 1 12 AND COUNT(last_name) > 1 13 AND COUNT(email) > 1;
输出
+------------+-------------------+-----------+------------------+-------------------------+--------------+ | first_name | COUNT(first_name) | last_name | COUNT(last_name) | email | COUNT(email) | +------------+-------------------+-----------+------------------+-------------------------+--------------+ | Janine | 2 | Labrune | 2 | [email protected] | 2 | | Roland | 2 | Keitel | 2 | [email protected] | 2 | +------------+-------------------+-----------+------------------+-------------------------+--------------+ 2 rows in set