mysql - 选择不同的互斥(基于另一列的值)行

标签 mysql sql

首先,我想说,如果在阅读问题后,有人对这个问题的更信息丰富的标题有建议,请告诉我,因为我认为我的标题有些缺乏,现在,开始吧。 .

鉴于此表结构:

+---------+-------------------------------------+------+-----+---------+----------------+
| 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 |
+----+---------+------------------+----------+

我想选择所有帐户(行)都具有“COMPLETE”状态的所有域。

如果域的状态行中包含“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)

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

最佳答案

这个怎么样:

select domain
from   test_table
group by domain
having sum(case when status = 'COMPLETE'
                then 0 else 1 end) = 0

关于mysql - 选择不同的互斥(基于另一列的值)行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15616511/

相关文章:

mysql - 计算类别中的唯一数据

mysql - SQL 查询,对两个子字符串进行排序

mysql - 将汇总行添加到表格末尾

sql - 用 mysql group by 返回计数 0

php - Laravel 查询构建器中的多个Where子句

mysql - 如何从 mysql 计算精确(分钟)?

sql - 在一组未更改的值中聚合

php - 将单个 CSV 文件导入 MySQL 中的多个表

sql 组合 2 个不同顺序的查询

mysql - 如何计算每半小时的消息数?