需要mySQL特殊查询

时间:2012-05-30 16:00:13

标签: mysql unique

在以下情况下我需要一些帮助:

非常简化的表users_log

+-----------------+-------------------+
| id | account_nr |    email          |
+-----------------+-------------------+
| 1  | 0000001    |  cust1_@mail.com  |
| 2  | 0000001    |  cust1_@mail.com  |
| 3  | 0000002    |  cust2_@mail.com  |
| 4  | 0000003    |  cust3_@mail.com  |
| 5  | 0000002    |  cust2_@mail.com  |
| 6  | 0000001    |cust1_new@mail.com |
+-----------------+-------------------+
  1. 允许客户在此表格中多次出现。
  2. 客户可以随时更改其电子邮件地址,旧条目不会更新。
  3. 正如您所见,帐户'0000001'出现3次,并在某个时候更改了他的电子邮件地址。

    我需要一个只返回从未更改过电子邮件地址的客户结果的查询。此外,我需要所有单个条目,因此没有分组。

    因此,客户'0000002'和'0000003'的所有条目都是上述示例中查询的预期结果。

    我想出了一种在脚本语言中使用多重循环的方法,但是想知道是否有更高效的查询可以使用,从而减少数据库负载? 这是一个非常大的数据库,我需要尽可能快的查询 - 谢谢你提前!

    PS:数据库结构是这样的,我无法改变任何东西。

2 个答案:

答案 0 :(得分:1)

CREATE TABLE users_log (ID INT, account_nr VARCHAR(1000), email VARCHAR(1000))

INSERT INTO users_log VALUES (1,'0000001','cust1_@mail.com');
INSERT INTO users_log VALUES (2,'0000001','cust1_@mail.com');
INSERT INTO users_log VALUES (3,'0000002','cust2_@mail.com');
INSERT INTO users_log VALUES (4,'0000003','cust3_@mail.com');
INSERT INTO users_log VALUES (5,'0000002','cust2_@mail.com');
INSERT INTO users_log VALUES (6,'0000001','cust1_new@mail.com');

SELECT account_nr
     , email
  FROM users_log a
 WHERE NOT EXISTS
       (SELECT *
          FROM users_log b
         WHERE a.email      != b.email
           AND a.account_nr = b.account_nr)

结果:

    ACCOUNT_NR  EMAIL
1   0000002     cust2_@mail.com
2   0000002     cust2_@mail.com
3   0000003     cust3_@mail.com

答案 1 :(得分:1)

这是一个使用JOIN而不是子查询的解决方案,它通常表现更好,因为JOIN可以使用索引,而派生的临时表则不能。

SELECT ul1.account_nr, ul1.email
FROM users_log ul1
LEFT JOIN users_log ul2
  ON ul2.account_nr = ul1.account_nr
  AND ul2.email <> ul1.email
WHERE ul2.account_nr IS NULL