Sql查询在联结表中搜索多个匹配项

时间:2016-02-05 10:43:43

标签: mysql sql postgresql yii yii2

enter image description here

您好,我有两个表和一个联结表。我想找到所有拥有一种或多种舒适的庄园。我写了这个查询(postrgreSql):

SELECT DISTINCT "estates".*
FROM   "estates"
       LEFT JOIN "estate_comforts"
              ON "estates"."id" = "estate_comforts"."estate_id"
WHERE  "estate_comforts"."comfort_id" IN ( '1', '2' ) 

它找到第一个舒适的庄园或第二个,但我需要在“AND”模式下搜索。

enter image description here

这个项目使用Yii2 framewors,所以普通的sql或ActiveRecord语句是可以接受的。

更新即可。此查询选择所有esates,无论舒适度

SELECT DISTINCT "estates".*
FROM   "estates"
       LEFT JOIN "estate_comforts"
              ON "estates"."id" = "estate_comforts"."estate_id"
AND "estate_comforts"."comfort_id" IN ( '1', '2' ) 

1 个答案:

答案 0 :(得分:2)

JOIN estate_comforts两次,一次为comfort_id 1,另一次为comfort_id 2:

SELECT DISTINCT "estates".*
FROM   "estates"
   INNER JOIN "estate_comforts" ec1
          ON "estates"."id" = ec1."estate_id"
   INNER JOIN "estate_comforts" ec2
          ON "estates"."id" = ec2."estate_id"
WHERE ec1."comfort_id" = '1'
  AND ec2."comfort_id" = '2'

或者,在estate_comforts上执行GROUP BY以查找具有至少两个不同comfort_id值的estate_id。加入这个结果:

select e.*
from "estates" e
  join (select "estate_id"
        from "estate_comforts"
        WHERE  "comfort_id" IN ( '1', '2' ) 
        group by "estate_id"
        having count(distinct "comfort_id") >= 2) ec ON e."id" = ec."estate_id"