【问题标题】:SQL Find Get Item that does not have specific statusSQL 查找获取没有特定状态的项目
【发布时间】:2019-12-30 16:13:23
【问题描述】:

我有下表:

case_id | run_id | status_id
1       | 44     |  1
1       | 45     |  3
1       | 46     |  1
2       | 44     |  3
2       | 45     |  3
2       | 46     |  3

上表是以下查询的结果:

SELECT t.case_id, t.run_id, t.status_id
FROM `test` t,
(SELECT id FROM `run` WHERE created_on BETWEEN '2019-10-01' AND CURRENT_DATE()) r
WHERE t.run_id = r.id 

我正在尝试仅选择 status_id 中只有 3 个的 case_id。

所以查询应该返回 case_id 2。

【问题讨论】:

  • 我建议你放弃旧式的连接操作的逗号语法,改用 JOIN 关键字。

标签: mysql sql


【解决方案1】:

您可以使用正确、明确、标准 JOIN 语法。 . .然后使用HAVING 子句进行聚合和过滤:

select t.case_id
from test t join
     run r
     on t.run_id = r.id 
where r.created_on BETWEEN '2019-10-01' AND CURRENT_DATE()
group by t.case_id
having min(t.status_id) = max(t.status_id) and min(t.status_id) = 3;

【讨论】:

    【解决方案2】:

    您可以使用带有having 子句的聚合和过滤器:

    select t.case_id
    from test t
    inner join run r on r.id = t.run_id
    where r.created_on between '2019-10-01' and current_date()
    group by t.case_id
    having count(r.status_id <> 3) = 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-07
      • 2011-08-08
      • 2019-01-31
      • 2020-05-16
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多