从相关表中选择匹配不同条件的行

时间:2018-11-24 12:32:25

标签: sql rows

我有一个名为places的表,看起来像这样:

enter image description here

和另一个名为place_addons_saved的表,如下所示:

enter image description here

如何编写与place_addons_saved.placeplaces.id相关的查询,并搜索仅与满足所有条件的地方匹配的行?

例如,当我搜索具有place_addon = 163place_option = 329place_addon = 162的行时,place_option = 324将返回ID为80的位置,但是当我搜索具有place_addon = 162place_option = 326place_addon = 163place_option = 330的行时,查询必须不返回任何内容,因为位置80不符合第二个条件< / p>

2 个答案:

答案 0 :(得分:0)

如果我理解正确,则可以使用group byhaving

select place
from place_addons_saved
where (place_addon = 163 and place_option = 329) or
      (place_addon = 162 and place_option = 324)
group by place
having count(*) = 2;  -- "2" is the number of comparisons

要获取有关地点的所有信息:

select p.*
from places p
where p.id in (select place
               from place_addons_saved
               where (place_addon = 163 and place_option = 329) or
                     (place_addon = 162 and place_option = 324)
               group by place
               having count(*) = 2;  -- "2" is the number of comparisons
              );

答案 1 :(得分:0)

这可能有效:

With GetResult (place,chk1,chk2) As
(
SELECT 
   pas.place,
   sum(Case When (pas.place_addon = 163) AND (pas.place_option = 329) then 1 Else 0 End) As chk1,
   sum(Case When (pas.place_addon = 162) AND (pas.place_option = 324) then 1 Else 0 End) As chk2
FROM 
   places AS p RIGHT OUTER JOIN
   place_addons_saved AS pas ON p.id = pas.place
   group by pas.place
 )
 Select * From GetResult Where chk1 > 0 and chk2 > 0