我有一张表posts
,就像那样:
和另一个表格post_filters
我已经为每个帖子存储了过滤器:
其中:
我想要所有apples
和
color
red
或Yellow
和country
England
和France
。如何在posts
和posts_filters
之间加入?两个表之间只能进行一次连接吗?
我尝试过这样的事情:
SELECT
posts.*,
a1.*,
a2.*
FROM posts
LEFT JOIN post_filters a1 ON posts.ID=a1.post_id AND a1.filter_id=1
LEFT JOIN post_filters a2 ON posts.ID=a2.post_id AND a2.filter_id=2
WHERE
a1.selected_filter_item IN (2,3)
AND
a2.selected_filter_item IN (1,3)
它不会有效地工作,我想只有一个加入。
答案 0 :(得分:0)
SELECT
p.*,
f.*,
fi.*
FROM posts p
JOIN post_filters pf ON pf.post_id = p.ID
JOIN filters f ON f.filter_id = pf.filter_id
JOIN filters_items fi ON fi.filters_item = pf.selected_filter_item AND fi.filter_id = f.filter_id
WHERE
f.filter_name IN ('country','color') AND
fi.filter_item_name IN ('England','France','red','yellow')
尝试此查询