2

首先,我想说的是,如果在阅读了这个问题后,有人对这个问题的信息更丰富的标题有任何建议,请告诉我,因为我认为我的有点缺乏,现在,开始做生意......

鉴于此表结构:

+---------+-------------------------------------+------+-----+---------+----------------+
| Field   | Type                                | Null | Key | Default | Extra          |
+---------+-------------------------------------+------+-----+---------+----------------+
| id      | int(11)                             | NO   | PRI | NULL    | auto_increment |
| account | varchar(20)                         | YES  | UNI | NULL    |                |
| domain  | varchar(100)                        | YES  |     | NULL    |                |
| status  | enum('FAILED','PENDING','COMPLETE') | YES  |     | NULL    |                |
+---------+-------------------------------------+------+-----+---------+----------------+

而这个数据:

+----+---------+------------------+----------+
| id | account | domain           | status   |
+----+---------+------------------+----------+
|  1 | jim     | somedomain.com   | COMPLETE |
|  2 | bob     | somedomain.com   | COMPLETE |
|  3 | joe     | somedomain.com   | COMPLETE |
|  4 | frank   | otherdomain.com  | COMPLETE |
|  5 | betty   | otherdomain.com  | PENDING  |
|  6 | shirley | otherdomain.com  | FAILED   |
|  7 | tom     | thirddomain.com  | FAILED   |
|  8 | lou     | fourthdomain.com | COMPLETE |
+----+---------+------------------+----------+

我想为所有帐户(行)选择具有“完成”状态的所有域。

不得返回具有包含除“完成”之外的任何值的行的任何域。

所以在上面的例子中,我的预期结果是:

+------------------+
| domain           |
+------------------+
| somedomain.com   |
| fourthdomain.com |
+------------------+

显然,我可以通过使用子查询来实现这一点,例如:

mysql> select distinct domain from test_table where status = 'complete' and domain not in (select distinct domain from test_table where status != 'complete'); 
+------------------+
| domain           |
+------------------+
| somedomain.com   |
| fourthdomain.com |
+------------------+
2 rows in set (0.00 sec)

这在我们的小模型测试表上可以正常工作,但在实际情况下,有问题的表将有数十(甚至数十)万行,我很好奇是否有更有效的方法来做这是因为子查询缓慢而密集。

4

2 回答 2

2

这个怎么样:

select domain
from   test_table
group by domain
having sum(case when status = 'COMPLETE'
                then 0 else 1 end) = 0
于 2013-03-25T13:57:10.547 回答
0

我认为这会奏效。实际上只是将两个基本查询连接在一起,然后比较它们的计数。

select
    main.domain
from 
    your_table main

    inner join 
    (
        select 
            domain, count(id) as cnt
        from 
            your_table
        where 
            status = 'complete'
        group by 
            domain
    ) complete
    on complete.domain = main.domain

group by
    main.domain

having
    count(main.id) = complete.cnt

您还应该确保您有一个索引,domain因为这依赖于该列上的连接。

于 2013-03-25T14:00:26.530 回答