gpt4 book ai didi

mysql - 优化 MySQL 查询中的多个 JOIN

转载 作者:行者123 更新时间:2023-11-29 19:45:58 26 4
gpt4 key购买 nike

在网站上,每个页面都必须包含相关的预告片,引导其他页面构成语义相关的内部链接。

涉及以下表格:

pages (id, parent, ...)
teasers (id, reference, prio, start_date, expiry_date, ...)
teaser_instances(id, teaser_id, pins, type, ...)
keywords (id, content, ...)
page_keyword_rel (page_id, keyword_id)

一个预告片可以在目标页面的不同部分包含多个实例,但同一个预告片不能在同一页面上多次呈现。当预告片“固定”到目标页面或属于同一父页面或预告片的页面包含与目标页面相同的关键字时,该预告片被视为相关。

因此,为了检索预告片,系统会生成如下查询:

SELECT ... 
FROM teasers t
LEFT JOIN teaser_instances i on t.id = i.teaser_id
LEFT JOIN pages p on t.reference = p.id
LEFT JOIN (page_keyword_rel r
LEFT JOIN keywords k on r.keyword_id=k.id) on p.id=r.page_id

WHERE
# relevancy criteria
(i.pins like '%XYZ%' or p.parent= '1' or k.content IN ('A', 'B', 'C')) and

# exclude instances of the same teaser on a page
t.reference != '1' and t.reference !='2' and t.reference !='3' and

# instance is characterized by type
i.type='1' and

# exclude self targeted teasers (teaser points to the target page)
p.id != '2' and

# time validity
(not t.start_date or t.start_date<=now()) and
(not t.expiry_date or t.expiry_date >=now())

GROUP BY t.reference
ORDER BY (i.pins not like '%XYZ%'), prio, rand() limit 0,5;

查询执行时间 Not Acceptable 。

解释给了我这个: enter image description here

问题肯定出在最后一个 JOIN 上,它无法使用索引(参见倒数第二行)。这是关键字匹配的相关性检查。

我们如何优化它?

提前致谢!

最佳答案

您上次加入on子句放置错误。它必须是

LEFT JOIN page_keyword_rel r on p.id=r.page_id

再次,将这些条件从 WHERE 移走至JOIN ON条件,因为您正在执行外连接。示例k.content IN ('A', 'B', 'C')将其移至JOIN ON条款

 LEFT JOIN keywords k on r.keyword_id=k.id
AND k.content IN ('A', 'B', 'C')

此外,请确保 JOIN ON 中使用的列条件或WHERE状况,group byorder by正在为其创建适当的索引。

关于mysql - 优化 MySQL 查询中的多个 JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40974487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com