0

我的目标是选择primary_category_idarticles表)或任何次要类别(articles_secondary_categories连接表)是给定值的文章。在此示例查询中,类别 1。我尝试使用其他类型的连接,但这里需要注意的是,一篇文章可能没有任何二级类别。

SELECT DISTINCT articles.* 
FROM articles
LEFT JOIN articles_secondary_categories AS categories 
    ON categories.article_id = articles.id
WHERE 
(
    primary_category_id = 1
    OR
    categories.category_id = 1
)
    AND articles.state = "published"
    AND edition_id = 1

ORDER BY publish_at DESC
LIMIT 10;

欢迎任何帮助优化此或替代方案。在具有 4karticles和 7k articles_secondary_categories(不是类别)的数据库中,运行此查询需要 5 秒。

4

2 回答 2

0

您可以反转对次要类别的查询:

(SELECT articles.* 
FROM articles
WHERE primary_category_id = 1)
UNION DISTINCT
(SELECT articles.*
FROM articles_secondary_categories AS categories 
JOIN articles ON (categories.article_id = articles.id)
WHERE categories.category_id = 1
GROUP BY articles_id)
ORDER BY publish_at DESC
LIMIT 10;

它应该给你一个不错的速度提升 - 只要确保你索引 categories.articles_id

于 2012-06-20T01:02:54.060 回答
0

避免OR在 where 子句中使用。优化器通常不使用带有OR谓词的索引。

尝试将categories.category_id = 1移入连接条件:

SELECT articles.* 
FROM articles
LEFT JOIN articles_secondary_categories AS categories 
    ON categories.article_id = articles.id and categories.category_id = 1
WHERE 1 in (ifnull(categories.category_id, primary_category_id), primary_category_id)
AND articles.state = "published"
AND edition_id = 1
ORDER BY publish_at DESC
LIMIT 10;

此查询的关键是1 in (ifnull(categories.category_id, primary_category_id), primary_category_id),它表示“如果我们有一个类别的连接,则在列表中使用它,否则使用 primary_category_id,并且在所有情况下都使用 primary_category_id。

于 2012-06-20T01:03:29.080 回答