通过两个表之间的连接过滤多个项目

时间:2016-06-22 14:37:30

标签: mysql sql

我有一张表posts,就像那样:

enter image description here

和另一个表格post_filters我已经为每个帖子存储了过滤器:

enter image description here

其中:

enter image description here

enter image description here

我想要所有apples

  • color redYellow
  • 来自country EnglandFrance

如何在postsposts_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)

它不会有效地工作,我想只有一个加入。

1 个答案:

答案 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')

尝试此查询