我有一个名为places
的表,看起来像这样:
和另一个名为place_addons_saved
的表,如下所示:
如何编写与place_addons_saved.place
和places.id
相关的查询,并搜索仅与满足所有条件的地方匹配的行?
例如,当我搜索具有place_addon = 163
,place_option = 329
和place_addon = 162
的行时,place_option = 324
将返回ID为80
的位置,但是当我搜索具有place_addon = 162
,place_option = 326
和place_addon = 163
,place_option = 330
的行时,查询必须不返回任何内容,因为位置80不符合第二个条件< / p>
答案 0 :(得分:0)
如果我理解正确,则可以使用group by
和having
:
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