获取具有A列中的公共值和B列中的特定值的所有行

时间:2019-11-11 08:41:48

标签: mysql sql

在MySQL中,我有具有 matcher type 列的表 matcher_table 。此处放置的记录的 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)的匹配数据,则必须获取满足此匹配条件的记录。

3 个答案:

答案 0 :(得分:2)

我建议使用三个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)上的索引。与其他方法相比,我希望它具有很好的性能。

答案 1 :(得分:1)

您可以在下面的查询中尝试-

select *
from `matcher_table`
where matcher in (select matcher
                  from `matcher_table`
                  where type in ('type1', 'type2', 'type3')
                  group by matcher
                  having count(distinct type) = 3)

Here是演示。

答案 2 :(得分:1)

您可以加入子查询,该子查询在matcher字段中分组。
并且只返回那些具有所有所需类型的变量。

    <dependency>
        <groupId>org.javamoney.lib</groupId>
        <artifactId>javamoney-calc</artifactId>
        <version>1.0</version>
        <type>pom</type>
    </dependency>