我有5张桌子:

Categories_groups_cat1

id|order|title(text)


Categories_vs_groups

id|categories_groups_cat1_id|categories_id


分类目录

id|title(text)


优惠

id|category (text)


优惠券

id|category (text)


我仅在以下情况下才显示Categories_groups_cat1中的标题:

通过Categories_groups_cat1_id列在Categories_vs_groups中至少存在一行(Categories_vs_groups.categories_groups_cat1_id == Categories_groups_cat1.id)
与Categories_vs_groups中的Categories_id至少相隔一列存在表类别(Categories.id == Categories_vs_groups.categories_id)中,并且在表中的通过类别列提供的优惠或优惠券中至少有一行(offers.category == categories.title)!

我执行以下操作,但是我超时,因为表提供的优惠券或赠券的金额更多,为500000。

SELECT
            offers.category_gr,
            categories.id, categories.title_gr,
            categories_vs_groups.categories_id,
            categories_vs_groups.categories_groups_cat1_id AS cat1,
            categories_vs_groups.categories_groups_cat2_id AS cat2

        FROM offers
        LEFT JOIN categories
        ON categories.title_gr=offers.category_gr
        LEFT JOIN categories_vs_groups
        ON categories_vs_groups.categories_id=categories.id

        WHERE categories.title_gr='$row_best_offer[category_gr]'

        GROUP BY categories.id
        order by categories.id

最佳答案

如果设置正确,则查询时间不会超过60秒。

您的where子句将撤消第一个LEFT JOIN(并且您可能也不需要第二个offers。因为您是按类别进行汇总,所以我建议从此开始。然后,categories(title_gr, category_gr, id)表仅用于过滤,因此您应该考虑是否确实必要。

因此,请考虑以下查询:

SELECT c.category_gr, c.id, c.title_gr,
       cvg.categories_id, cvg.categories_groups_cat1_id AS cat1,
       cvg.categories_groups_cat2_id AS cat2
FROM categories c JOIN
     offers o
     ON c.title_gr = o.category_gr LEFT JOIN
     categories_vs_groups cvg
     ON cvg.categories_id = c.id
WHERE c.title_gr = '$row_best_offer[category_gr]'
GROUP BY c.id
ORDER BY c.id;


为了获得最佳结果,您需要在offers(category_gr)categories_vs_groups(categories_id)和上建立索引。

07-24 12:57