如果所有状态都为“否”,如何通过request_id选择请求?

时间:2017-12-18 11:46:55

标签: mysql sql

结果表:

id | request_id | status
 1 | 1          | Yes
 2 | 1          | Yes
 3 | 2          | Yes
 4 | 2          | No
 5 | 2          | Yes
 6 | 3          | No
 7 | 3          | No
 8 | 3          | No

如果所有状态均为“否”,如何通过request_id选择请求,在此示例中为“3”?

4 个答案:

答案 0 :(得分:4)

一种简单的方法是使用NOT IN(或NOT EXISTS)查找记录:

select *
from mytable
where request_id not in (select request_id from mytable where status = 'Yes');

(如果您希望将更多where status = 'Yes'更改为where status <> 'No',可以有更多状态。)

答案 1 :(得分:3)

要获取具有status = No的所有行的request_ids,您可以使用聚合

select request_id 
from demo
group by request_id 
having count(*)  = sum(status = 'No')

此处count(*)将获取每个request_id的所有行数,sum(status = 'No')将计算status =&#39; No&#39;对于request_id,如果两个值相同,则表示请求的所有行的状态都设置为No

根据您的评论&gt;要获得所有行不仅是request_id,您还可以使用上面的

进行连接
select a.*
from demo a
join (
   select request_id 
    from demo
    group by request_id 
    having count(*)  = sum(status = 'No') 
) b using(request_id)

Demo

答案 2 :(得分:3)

如果你对一串ID很好:

select group_concat(id)
from mytable
group by request_id 
having max(status) = 'No';

(&#39;是&#39;来自&#39;否&#39;在字母表中,所以如果它只是这两个值,则可以使用MAX。)

答案 3 :(得分:1)

E.g:

SELECT DISTINCT x.*
           FROM my_table x
           LEFT
           JOIN my_table y 
             ON y.request_id = x.request_id
            AND y.status <> x.status
          WHERE x.status = 'No'
            AND y.id IS NULL;