简体   繁体   English

MySQL计数优化

[英]MySQL count optimization

I want to decrease the load time from 2.5 secs for a mysql count query. 对于mysql计数查询,我想减少2.5秒的加载时间。 All columns in the query have a index. 查询中的所有列都有一个索引。

SELECT COUNT(1)
FROM song AS s
JOIN song_text AS st
  ON(st.song_id = s.song_id)
JOIN phpfox_user AS u
  ON(u.user_id = s.user_id)
WHERE st.lyrics LIKE '%a%' AND s.is_active = 1 AND s.public = 1

The query getting the returned rows load in 0.0009060 seconds. 获取返回行的查询加载0.0009060秒。

SELECT s.*, st.lyrics, u.first_name
FROM song AS s
JOIN song_text AS st
  ON(st.song_id = s.song_id)
JOIN phpfox_user AS u
  ON(u.user_id = s.user_id)
WHERE st.lyrics LIKE '%a%' AND s.is_active = 1 AND s.public = 1
ORDER BY s.date_added DESC 
LIMIT 12

Why does the count query have a significantly more load time than the query returning the rows? 为什么count查询的加载时间明显多于返回行的查询? What can be done to reduce the load time for the count query to something similar to other query? 可以做些什么来将计数查询的加载时间减少到与其他查询类似的内容?

Do you care about the u.first_name value in the count? 你关心计数中的u.first_name值吗? If no, remove the 2nd join, it appears to add no value. 如果不是,删除第二个连接,它似乎没有添加任何值。

Also, try count(s.song_id) from the song table instead of count(1). 另外,尝试从歌曲表中计数(s.song_id)而不是count(1)。 I'm not sure if this is a real optimization or just my imagination. 我不确定这是真正的优化还是我的想象力。

Your second query completes once it has go the first 12 records. 一旦它进入前12条记录,您的第二个查询就会完成。 Whereas your first (count) query has to join all the columns in all tables. 而您的第一个(计数)查询必须连接所有表中的所有列。

This is the only difference I can see! 这是我能看到的唯一区别!

I think it is because of 我认为这是因为

LIMIT 12

You only catch only 12 lines of your select statement. 您只能捕获select语句的12行。

First one has to look at execution plans of the queries. 首先必须查看查询的执行计划。

I suppose that the temporary tables in the 1st query are quite big, therefore the aggregation is applied on a large amount of data. 我想第一个查询中的临时表非常大,因此聚合应用于大量数据。

In the other side LIMIT 12 already tells the query processor that it does not make sense to elaborate all of the rows but only 12, so that the temporary tables are small. 在另一方面, LIMIT 12已经告诉查询处理器,详细说明所有行但只有12个没有意义,因此临时表很小。

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

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