mysql - 查询特定唯一 id 的所有值都相同的情况

标签 mysql sql

我有下面提到的数据库:

id  Value
1   A
1   B
1   B
2   A
2   B
3   B
3   B

我想要

  1. 仅当这些 id 的所有值为“B”时,才会出现这些 id。 (即本例中的 id 3)
  2. 在查询时使用 where id!=A 但它会给出两个值都存在的所有 id。

最佳答案

您可以使用group byhaving:

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/

相关文章:

mysql - mySQL 中完全外连接的计数

mysql - 根据条件从表中选择计数

c# - 打印没有预览的 ReportViewer

mysql - 创建删除 session 的事件时 SQL 语法错误

mysql - mysql 查询中的动态值

如果在另一列中,则基于总和的Mysql平均值

mysql - 无法删除最大用户连接数

sql - 如何翻译 SQL 语句以在 sqlx API 调用中使用?

两个表之间的 SQL 相同单元需要 1 个单元格中的订单号

SQL Server : querying hierarchical and referenced data