目前我有一个选择查询在我的客户数据库中查找X量的电子邮件并返回类似的内容
SELECT
first_name,
last_name,
email_address,
date_deleted
FROM CUSTOMERS
WHERE email_address in ('bob.smith@gmail.com', 'john.green@gmail.com', 'simon.anderson@gmail.com', 'carl.thomas@gmail.com');
+----+------------+-----------+---------------------------+--------------+
| id | first_name | last_name | email_address | date_deleted |
+----+------------+-----------+---------------------------+--------------+
| 1 | bob | smith | bob.smith@gmail.com | 2013-02-18 |
| 2 | NULL | NULL | bob.smith@gmail.com | NULL |
| 3 | john | green | john.green@gmail.com | NULL |
| 4 | simon | anderson | simon.anderson@gmail.com | NULL |
| 5 | carl | thomas | carl.thomas@gmail.com | 2012-09-20 |
| 6 | NULL | NULL | carl.thomas@gmail.com | NULL |
+----+------------+-----------+---------------------------+--------------+
在电子邮件地址列中,有重复的电子邮件地址。我想修改我的查询,以便它仅在该列中返回重复项并通过date_deleted进行过滤。这可能吗?
+----+------------+-----------+---------------------------+--------------+
| id | first_name | last_name | email_address | date_deleted |
+----+------------+-----------+---------------------------+--------------+
| 1 | bob | smith | bob.smith@gmail.com | 2013-02-18 |
| 2 | carl | thomas | carl.thomas@gmail.com | 2012-09-20 |
+----+------------+-----------+---------------------------+--------------+
答案 0 :(得分:2)
在列中查找重复值的最佳方法是使用HAVING语句,正如Mike Tung在评论中提到的那样。
SELECT email_address
FROM CUSTOMERS
GROUP BY email_address
HAVING COUNT(1) > 1
这将返回以下结果:
+---------------------------+
| email_address |
+---------------------------+
| bob.smith@gmail.com |
| carl.thomas@gmail.com |
+---------------------------+
然后,您可以使用此查询的结果执行您需要的任何其他逻辑。如果我正确理解您的问题,您希望查找具有重复电子邮件地址且具有非null date_deleted的记录。如果是这样,您可以使用以下查询获取该信息:
SELECT CUS.first_name
,CUS.last_name
,CUS.email_address
,CUS.date_deleted
FROM CUSTOMERS AS CUS
JOIN (SELECT email_address
FROM CUSTOMERS
GROUP BY email_address
HAVING COUNT(1) > 1) AS C
ON C.email_address = CUS.email_address
WHERE CUS.date_deleted IS NOT NULL
这应该给你结果:
+----+------------+-----------+---------------------------+--------------+
| id | first_name | last_name | email_address | date_deleted |
+----+------------+-----------+---------------------------+--------------+
| 1 | bob | smith | bob.smith@gmail.com | 2013-02-18 |
| 2 | carl | thomas | carl.thomas@gmail.com | 2012-09-20 |
+----+------------+-----------+---------------------------+--------------+
答案 1 :(得分:0)
这可以通过MySQL
实现SELECT
first_name,
last_name,
email_address,
date_deleted
FROM CUSTOMERS
WHERE email_address in ('bob.smith@gmail.com', 'john.green@gmail.com', 'simon.anderson@gmail.com', 'carl.thomas@gmail.com')
GROUP BY email_address
HAVING COUNT(email_address) > 1