我有下面提到的数据库:
id Value
1 A
1 B
1 B
2 A
2 B
3 B
3 B
我想要
- 仅当这些 id 的所有值为“B”时,才会出现这些 id。 (即本例中的 id
3
) - 在查询时使用 where
id!=A
但它会给出两个值都存在的所有 id。
最佳答案
您可以使用group by
和having
:
select id
from t
group by id
having min(value) = max(value) and min(value) = 'B';
如果您有单独的 id 表,这可能会更快:
select i.id
from ids i
where not exists (select 1 from idvalues iv where iv.id = i.id and iv.value <> 'B') and
exists (select 1 from idvalues iv where iv.id = i.id and iv.value = 'B'); -- at least one B
这可以利用 idvalues(id, value)
上的索引。
关于mysql - 查询特定唯一 id 的所有值都相同的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49096691/