给定两个表ab,我想对a执行一个查询,该查询给出b中至少有一行包含b.a_id = a.idflag=1以及至少有一行包含b.a_id = a.idflag=0的行.

我有一个解决方案(见下文),但我想知道是否有人知道更优雅/有效的解决方案?

这里的示例是我的实际数据集的简化和提炼版本.实际上,表‘a’有数百万行,并且有相关的索引.

    CREATE table a (
      id int unsigned NOT NULL,
      PRIMARY KEY (id)
    );
    
    CREATE TABLE b (
      id int unsigned NOT NULL AUTO_INCREMENT,
      a_id int unsigned NOT NULL,
      flag tinyint NOT NULL,
      PRIMARY KEY (id)
    );
    
    INSERT INTO a VALUES (1),(2),(3),(4);
    INSERT INTO b (a_id, flag) VALUES
      (1,0),(1,1),(1,1),
      (2,0),(2,1),(2,0),
      (3,1),
      (4,0);

select * from a;

id
1
2
3
4

从b中 Select *;

id a_id flag
1 1 0
2 1 1
3 1 1
4 2 0
5 2 1
6 2 0
7 3 1
8 4 0

查询的预期结果:

id
1
2

View on DB Fiddle

当前解决方案:

    select * from a where
        exists (select * from b where a_id = a.id and flag = 1) 
        and exists (select * from b where a_id = a.id and flag = 0);

推荐答案

为了简化问题,我们可以考虑在表b中为a.id提供0和amp;1标志.

Solution 1

select * from a 
where (
  select count(distinct flag) as c 
  from b 
  where b.a_id = a.id and b.flag in (0, 1) #list of flags
) = 2; # count of the unique flags

Solution 2

select a.id 
from a 
inner join 
    (
      select b.a_id 
      from b 
      where b.flag in (0,1) 
      group by b.a_id
      having count(distinct b.flag) = 2
    ) as x on x.a_id = a.id

select a.id 
from a 
where a.id in 
    (
      select b.a_id 
      from b 
      where b.flag in (0,1) 
      group by b.a_id
      having count(distinct b.flag) = 2
    )

The perf或mance of these queries needs to be checked with real data.

Mysql相关问答推荐

为分组记录MySQL取取值为TRUE的单行

在时间戳上搜索大的MySQL表很慢

在MySQL CLI中,是否有自动完成过程的方法?

Mysql-查找缺少列的表

Golang中使用Gorm的Where条件转义字符无法正常工作的问题

如果存在N个特殊行,如何 Select 它们,其余的必须填充常规行,总行数不能超过MySQL中的X行?

仅计算 DATEDIFF (MySQL) 中的工作日

java.lang.NullPointerException:无法调用com.proj.my.repository.OrderRepository.save(Object),因为this.orderRepository为空

如何在 MySQL 中查找重复值和更新值

MySQL 使用了错误的索引

根据单个日期字段获取范围/天数

提取 MySQL 5.7 连续值的差异

根据使用 mysql 的第一个过滤结果添加更多表行

在 MySQL 中使用三个表进行计算

MariaDB 下的慢速更新、删除和插入查询

如何存储百分比值?

将 Django DB 从 SQLite 迁移到 MySQL 的最佳方法是什么?

Drupal 的默认密码加密方法是什么?

MySQL - 在 MySQL UPDATE 或 SELECT 查询中使用 If Then Else

如何通过一个语句描述数据库中的所有表?