无法检查字段中是否所有记录都有特定值

2ekbmq32  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(275)

我想看看 matches have as status:3和5,所以假设我有一个 matches 这样地:

id | round_id | status 
 1      28        3
 2      28        3 
 3      28        5
 4      28        5

查询结果应返回 true 因为所有的 matches 可用状态为 3 或者 5 . 我写了这个问题:

SELECT (SELECT COUNT(DISTINCT `status`) FROM `match` WHERE round_id = 28 AND (`status` = 3 OR`status` = 5)) = 1 AS result

但这会回来的 0

mwg9r5ms

mwg9r5ms1#

试试这个:

select round_id from matches
where status in (3, 5)
group by round_id
having count(distinct status) > 1
xlpyo6sf

xlpyo6sf2#

你可以做:

select ( count(*) = sum(status in (3, 5)) ) as flag_3_5
from matches
where round_id = 28;

您可以使用 group by round_id .
mysql将布尔表达式视为数字上下文中的数字,true为“1”,false为“0”。所以, sum(status in (3, 5)) 统计具有这两种状态的行数。比较将检查这些是否都是行。

u5i3ibmn

u5i3ibmn3#

你可以用 exists :

select distinct m.round_id, (case when exists (select 1 
                                               from match m1 
                                               where m1.round_id = m.round_id and 
                                                     m1.status in (3,5)
                                               ) 
                                  then 'true' else 'false' 
                             end) as result
from match m
where round_id = 28;

相关问题