2015-09-02 46 views
0

搜索帖子時,用戶可以從要篩選的類別列表中進行選擇,以返回與所選類別相關的帖子。替代在搜索查詢中追加內部聯接

SELECT * 
FROM posts 
INNER JOIN category_joins as filter_categories_join 
    ON filter_categories_join.categorizable_id = posts.id 
    AND filter_categories_join.categorizable_type = 'Post' 
INNER JOIN categories as filter_categories 
    ON filter_categories.id = filter_categories_join.category_id 
INNER JOIN category_joins as categories_join_1 
    ON categories_join_1.categorizable_id = posts.id 
    AND categories_join_1.categorizable_type = 'Post' 
INNER JOIN categories as categories_1 
    ON categories_1.id = categories_join_1.category_id 
INNER JOIN category_joins as categories_join_2 
    ON categories_join_2.categorizable_id = posts.id 
    AND categories_join_2.categorizable_type = 'Post' 
INNER JOIN categories as categories_2 
    ON categories_2.id = categories_join_2.category_id 
WHERE filter_categories.lft BETWEEN 14 AND 115 
    AND categories_1.lft BETWEEN 133 AND 134 
    AND categories_2.lft BETWEEN 137 AND 138 

是否有避免爲每個類別過濾器附加內部聯接的方法?

UPDATE:

關聯的描述在這裏:

  • posts有很多categories
  • posts通過category_joins爲categorizable
  • categories有相關categories許多posts通過category_joins
+0

你迫使我們猜測,請你可以包含示例數據並描述你的數據的行爲結構。例如,我假設'posts'和'category_joins'之間的連接是'1:many'?並且'category_joins'和'filter_categories'之間的連接是'1:1'?您需要提供更多信息才能獲得完整答案。 – MatBailie

回答

0

不確定爲什麼要複製JOINS這是不必要的。您的查詢可以簡化爲

SELECT p.* 
FROM posts p 
INNER JOIN category_joins cj 
    ON cj.categorizable_id = p.id 
    AND cj.categorizable_type = 'Post' 

INNER JOIN categories c 
    ON c.id = cj.category_id 
AND c.lft BETWEEN 14 AND 115 
    INNER JOIN categories c1 
    ON c1.id = cj.category_id 
    AND c1.lft BETWEEN 133 AND 134 
INNER JOIN categories c2 
    ON c2.id = cj.category_id 
AND c2.lft BETWEEN 137 AND 138;