mysql - 获取 A 列中具有公共(public)值且 B 列中具有特定值的所有行

标签 mysql sql

在 MySQL 中,我有表 matcher_table,其中包含列 matchertype。放在这里的记录可以有许多不同的 type 值。仅当 matcher 列的值相同时,一种类型才匹配另一种类型。
假设我必须找到 5 个类型 的所有匹配 记录。哪个是实现此目标的最佳方法/查询?


表格将是:

CREATE TABLE `matcher_table` (
  `id` INT NOT NULL,
  `matcher` VARCHAR(45) NULL,
  `type` VARCHAR(45) NULL,
  PRIMARY KEY (`id`));

现在假设表中有以下值:

id | matcher | type
1  | match1  | type1
2  | match1  | type2
3  | match1  | type3
4  | match2  | type4
5  | match2  | type2
6  | match3  | type1
7  | match3  | type2
8  | match3  | type3

如果我需要获取类型(type1、type2、type3)的匹配数据,那么我必须获取 ID 为 1、2、3、6、7、8 的行(由于 match1 和 match3)。
如果我需要获取类型(type1、type2、type3、type4)的匹配数据,那么我必须没有满足此匹配的记录。

最佳答案

我会推荐三个 exists 子句——因为您需要原始行:

select mt.*
from matcher_table mt
where exists (select 1
              from matcher_table mt2
              where mt2.matcher = mt.matcher and mt2.type = 'type1'
             ) and
      exists (select 1
              from matcher_table mt2
              where mt2.matcher = mt.matcher and mt2.type = 'type2'
             ) and
      exists (select 1
              from matcher_table mt2
              where mt2.matcher = mt.matcher and mt2.type = 'type3'
             );

这种方法的优点是它避免了聚合,并且可以利用 matcher_table(matcher, type) 上的索引。与其他方法相比,我希望它具有非常好的性能。

关于mysql - 获取 A 列中具有公共(public)值且 B 列中具有特定值的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58798024/

相关文章:

javascript - 调用第 43 行未定义的方法 mysqli_stmt::get_result()

java - 如何通过Java中的sql查询确保mysql db中的数据立即更新

mysql - 为电子商务网站编写 SOLR 搜索查询的最佳实践是什么

第 n 次循环迭代的 SQL 逗号分割函数

c# - 业务层设计困境 : memory or IO?

sql - 在不循环的情况下去除 SQL 中的特殊字符?

mysql - SQL:两次使用不同的 where 条件查询表?

java - sql 中 column2 中 column1 的唯一值

Mysql 查询带有 order by。奇怪的执行计划

Mysql更新子查询的if条件如何