Postgresql选择相关标签(多对多)

时间:2017-10-13 17:29:35

标签: sql postgresql relationship

我有一个名为评论的VIEW,它与汽车表有关,汽车表与表标签有很多关系(通过名为cars_tags的连接表),但我需要的是从汽车中检索评论它与某些标签相关,并且与另一个标签相关。我今天拥有的是以下SQL代码:

SELECT  "cars"."review".* 
FROM "cars"."review" 
LEFT JOIN cars.cars ON (cars.review.car_id = cars.cars.id) 
LEFT JOIN cars.makes ON (cars.cars.make_id = cars.makes.id) 
LEFT JOIN cars.cars_tags ON (cars.cars.id = cars.cars_tags.car_id) 
LEFT JOIN cars.tags ON (cars.cars_tags.tag_id = cars.tags.id) 
WHERE (cars.tags.id IN ('91782e95-8c5d-4254-82ab-b11a21306c18')) 
AND (cars.tags.id IN ('031cec30-df27-471e-858d-53c3d9657c8a')) 
ORDER BY "cars"."review"."score" DESC LIMIT 100

这个SQL没有给我带来任何结果,但我确信有些车与第一个id有关:' 91782e95-8c5d-4254-82ab-b11a21306c18' AND' 031cec30-df27- 471e-858D-53c3d9657c8a'同时......我做错了什么?

由于

2 个答案:

答案 0 :(得分:0)

bool_or

select r.col1, r.col2 
from
    cars.review r
    left join
    cars.cars on r.car_id = cars.id
    inner join
    cars.cars_tags on cars.id = cars_tags.car_id
    inner join
    cars.tags on cars_tags.tag_id = tags.id 
group by r.col1, r.col2 
having
    bool_or (tags.id = '91782e95-8c5d-4254-82ab-b11a21306c18')
    and
    bool_or (tags.id = '031cec30-df27-471e-858d-53c3d9657c8a')
order by r.score desc
limit 100

exists版本:

select col1, col2 
from cars.review
where exists (
    select 1
    from 
        cars.cars
        inner join
        cars.cars_tags on cars.id = cars_tags.car_id
        inner join
        cars.tags on cars_tags.tag_id = tags.id
    where review.car_id = cars.id
    group by 1
    having
        bool_or (tags.id = '91782e95-8c5d-4254-82ab-b11a21306c18')
        and
        bool_or (tags.id = '031cec30-df27-471e-858d-53c3d9657c8a')
)
order by score desc
limit 100

答案 1 :(得分:0)

根据我的理解,您对拥有2个特定标签的汽车的评论感兴趣。

这可以通过以下查询完成。我已经删除了对cars.make的引用,因为您没有从中检索任何数据。此外,我已删除对cars.tags的引用,因为您使用的唯一信息是cars_tags表中的标记ID。

sleep()

查询只会找到所有评论,其中包含您之后的两个tag_id的cars_tags条目。