简体   繁体   English

为什么即使子查询执行得很快,带子查询的SQL查询还是这么慢?

[英]Why is my sql query with a subquery so slow even though the subquery performs fast?

My query is something like: 我的查询是这样的:

SELECT *,
(SELECT COUNT(*) FROM comments WHERE comments.thread = threads.id) AS comments
FROM threads
LIMIT 10

comments.thread is an index, queries like this run fast: comments.thread是一个索引,这样的查询运行很快:

SELECT COUNT(*) FROM comments WHERE comments.thread = 'someId'

However, my query is extremly slow. 但是,我的查询速度非常慢。 It takes 10 seconds times the limit I define. 我需要10倍的时间来定义我的限制。 Why? 为什么?

For this query: 对于此查询:

SELECT t.*,
      (SELECT COUNT(*) FROM comments c WHERE c.thread = t.id) AS comments
FROM threads t
LIMIT 10;

You want an index on comments(thread) . 您要在comments(thread)上建立索引。 If your other query runs fast, then I would guess that you already have one. 如果您的其他查询运行很快,那么我猜您已经有了一个查询。

Perhaps the LIMIT and subquery are acting strangely. LIMIT和子查询的行为可能很奇怪。 Is this version also slow? 这个版本还慢吗?

SELECT t.*,
      (SELECT COUNT(*) FROM comments c WHERE c.thread = t.id) AS comments
FROM (SELECT t.*
      FROM threads t
      LIMIT 10
     ) t;

Your inner query is a corelated subquery, meaning it uses a value from the outer query, so executes for every row of the outer query. 内部查询是一个相关的子查询,这意味着它使用外部查询中的值,因此将对外部查询的每一行执行一次 Maybe MySQL is not so good at optimizing the query. 也许MySQL不太擅长优化查询。

Try this: 尝试这个:

SELECT threads.*, count(comments.thread) AS comments
FROM threads
JOIN comments ON comments.thread = threads.id
GROUP BY 1,2,3,4,5 -- one number here for each column of the threads table
LIMIT 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM