在 MySQL 中,我有表 matcher_table,其中包含列 matcher 和 type。放在这里的记录可以有许多不同的 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/