![](/img/trans.png)
[英]Query with MySQL join is slow, is there a way to improve slow performance with subquery?
[英]How to improve slow MySQL subquery
我知道慢查詢有很多問題/答案,但我很難將現有答案與我的示例聯系起來。
我有以下簡單查詢,它計算子查詢中的文章瀏覽量:
SELECT
articles.id,
articles.views,
articles.title,
articles.slug,
articles.created_at,
(SELECT count(*) FROM tracking WHERE element_id = articles.id AND tracking_type = 'article_view') AS tracking_views
FROM articles
WHERE articles.company_id = 123
ORDER BY articles.created_at DESC
這家公司有大約 250 篇文章,查詢時間超過 12 秒。
有沒有更好/更有效的方法可以做到這一點?
嘗試加入群組。 在不知道有多少文章/觀點和公司的情況下很難說。
What you want is for SQL to be able to to the aggregation of tracking
in one go, rather than individually for every row in the result, which is implied by the position of your tracking_view
sub select.
如果你幸運(我沒有檢查)加入counts
子 select 將足夠聰明,可以跳過任何不適合公司的文章。 如果不是,您可以在counts
子 select 中包含回公司的加入。
例如
select a.*, counts.count
from articles a
join (
select count(*) as count, element_id
from tracking
where tracking_type = 'article_view'
group by tracking.element_id
) as counts on counts.element_id = a.id
where a.company_id = 123
ORDER BY articles.created_at DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.