选择where字段有多于2个非重复记录sql

时间:2013-10-01 20:28:24

标签: mysql

这应该很容易,但我只是无法解决这个问题。

找到了包含客户订单信息的表格。此表中有一个名为customers_email_address和customers_id的字段以及许多其他非必要字段。我需要找到不同的记录,其中customers_email_address字段中的条目不同,但对于相同的customers_id是唯一的。换句话说,我需要了解客户自帐户开始以来在其帐户中更改了自己的电子邮件地址,以便我可以使用新的电子邮件地址更新我的电子邮件广告计划。网站设计时我没有想到的东西!

也许一个例子是:

customers_ID    customers_email_address
1               joeschome@hotmail.com
2               frankj@hotmail.com
1               joeschome@hotmail.com
2               frankj@hotmail.com
1               joeschome@yahoo.com
2               frankj@yahoo.com
3               janefr@live.com
3               janefr@live.com
3               janefr@live.com

查询结果应如下所示:

customers_id    customers_email_address
1               joeschome@hotmail.com
1               joeschome@yahoo.com
2               frankj@hotmail.com
2               frankj@yahoo.com

仅返回customers_email_address字段具有多个非重复记录但相同customer_id的位置

也许更好的事情会是这样的:

customers_id    customers_email_address1        customers_email_address2
1               joeschome@hotmail.com           joeschome@yahoo.com
2               frankj@hotmail.com      frankj@yahoo.com

我希望这是有道理的。如果您有更好的想法,请随时加入。

无论如何,谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

更新:您可以这样做

SELECT DISTINCT o.customers_id, o.customers_email_address
  FROM orders o JOIN
(
  SELECT customers_id
    FROM orders
   GROUP BY customers_id
  HAVING COUNT(DISTINCT customers_email_address) > 1
) q
    ON o.customers_id = q.customers_id
 ORDER BY o.customers_id;

输出:

| CUSTOMERS_ID | CUSTOMERS_EMAIL_ADDRESS |
|--------------|-------------------------|
|            1 |     joeschome@yahoo.com |
|            1 |   joeschome@hotmail.com |
|            2 |        frankj@yahoo.com |
|            2 |      frankj@hotmail.com |

这是 SQLFiddle 演示

答案 1 :(得分:0)

这将返回两列customers_email_address1和customers_email_address2并且快速,因为它可以使用覆盖索引

SELECT 
 orders1.customers_ID
, orders1.customers_email_address "customers_email_address1"
, orders2.customers_email_address "customers_email_address2"
FROM 
 orders orders1

INNER JOIN 
 orders orders2

ON
 orders1.customers_ID = orders2.customers_ID
AND
  orders1.customers_email_address != orders2.customers_email_address

GROUP BY
 orders1.customers_ID

; 

请参阅http://sqlfiddle.com/#!2/b1c8e/43

或者如果你需要一个非规范化列表(从应用程序代码更新时可能很容易)你可以使用它,即使在大型表上也应该非常快,因为使用覆盖索引

  SELECT
    customers_id
    , GROUP_CONCAT(DISTINCT customers_email_address SEPARATOR '|') as emails
   FROM orders
   GROUP BY customers_id 
   HAVING COUNT(DISTINCT customers_email_address) > 1

请参阅http://sqlfiddle.com/#!2/b1c8e/41