结果表:
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
如果所有状态都为“No”,如何通过request_id选择请求,在本例中为“3”?
一个简单的方法是使用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'
。)
如果你对一串ID很好:
select group_concat(id)
from mytable
group by request_id
having max(status) = 'No';
('是'在字母表中的'否'后面,所以如果它只是这两个值,你可以使用MAX
。)
要获取具有status = No的所有行的request_ids,您可以使用聚合
select request_id
from demo
group by request_id
having count(*) = sum(status = 'No')
这里count(*)将获得每个request_id的所有行的计数,sum(status = 'No')
将计算每个request_id的status ='No'的行,如果两个值相同,则表示请求的所有行的状态都设置为No
从你的评论>要获得所有行不仅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)
Ef。:
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;