有没有办法在不使用多个 SELECT 语句的情况下选择与选中项关联的元素?

问题描述

我正在尝试进行查询,以选择仅在复选框列表中选中所有交通工具的地方的街区 ID。例如,如果选中“Bus”和“Railway”,它应该给我 7,8,如果只选中“Railway”,它应该给我 7,8,11。 ‘transporte’表是这样的

     b_codigo | tipo_transporte
    ----------+-----------------
            1 | Underground
            1 | Bus
            2 | Bus
            2 | Underground
            3 | Bus
            3 | Underground
            4 | Bus
            4 | RENFE
            4 | Underground
            5 | RENFE
            5 | Underground
            5 | Bus
            5 | Tram
            6 | Bus
            6 | Underground
            7 | RENFE
            7 | Underground
            7 | Bus
            7 | Railway (FGC)
            8 | Underground
            8 | Railway (FGC)
            8 | Bus
            9 | Underground
            9 | Bus
           10 | Underground
           10 | Bus
           11 | Railway (FGC)
           11 | Underground
           12 | Bus

我尝试使用表单查询

SELECT disTINCT b_codigo 
FROM transporte 
WHERE (b_codigo,'checked1') IN (SELECT * FROM transporte) 
  AND (b_codigo,'checked2') IN (SELECT * FROM transporte) 
  AND ...

另一种形式

SELECT b_codigo 
FROM transporte 
WHERE tipo_transporte = 'checked1' 
INTERSECT 
SELECT b_codigo 
FROM transporte 
WHERE tipo_transporte = 'checked2' 
INTERSECT 
...;

两者都给我相同的结果,但我担心这两个查询的效率。

有没有一种方法可以在不使用 N 条选中的 N 个 SELECT 语句的情况下执行相同的查询

解决方法

一种方法是使用聚合:

select b_codigo
from transporte
where tipo_transporte in ('Bus','Railway (FGC)')
group by b_codigo
having count(distinct tipo_transporte) = 2

要与 HAVING 子句进行比较的数字,需要与 IN 子句的元素数相匹配。