MYSQL从多个查询结果中获取常见ID

时间:2017-11-06 09:32:03

标签: mysql

我有3个查询给我3个结果

SELECT group_concat(cna_id) FROM `cna_filters` where filter_type=1 and filter_id in(1,6,10) and is_checked=1 group by filter_type,cna_id

结果 - 42,43,44,45

SELECT group_concat(cna_id) FROM `cna_filters` where filter_type=2 and filter_id in(8) and is_checked=1 group by filter_type,cna_id

结果 - 42,43

SELECT group_concat(cna_id) FROM `cna_filters` where filter_type=3 and filter_id in(11) and is_checked=1 group by filter_type,cna_id

结果 - 42,43,44,45

我希望从3个以上的结果中输出常见的ID

结果= 42,43

我已经尝试了联盟但没有工作。

2 个答案:

答案 0 :(得分:0)

SELECT group_concat(cna_id) FROM `cna_filters`
WHERE group_concat(cna_id) = 'object1'
UNION
SELECT group_concat(cna_id) FROM `cna_filters`
WHERE group_concat(cna_id) = 'object2'
UNION
SELECT group_concat(cna_id) FROM `cna_filters`
WHERE group_concat(cna_id) = 'object3'

答案 1 :(得分:0)

您想要三个数据集的交集。如果MySQL支持标准SQL INTERSECT

,这将非常简单

但是这也可以通过条件聚合来解决,以检查所有三个数据集中是否存在cna_id(并且使用此方法只能读取一次表):

select cna_id
from cna_filters
where is_checked=1
group by cna_id
having sum( filter_type = 1 and filter_id in (1, 6, 10) ) > 0
   and sum( filter_type = 2 and filter_id = 8 ) > 0
   and sum( filter_type = 3 and filter_id = 11 ) > 0;