简体   繁体   中英

mysql Query very slow, any recommendation on how to optimize?

I've recently moved to a dedicated Windows hosting with Plex CPanel through godaddy. I've setup my site and database (MySQL)

I am now recently noticing my database queries are now taking a lot longer than expected.

My tables:

在此处输入图片说明在此处输入图片说明

Here is an example:

SELECT a.snapshot_id, a.brand_id, b.brand_id 
FROM snapshots a 
    INNER JOIN brands b 
               ON a.brand_id = b.brand_id 
WHERE DATE(a.date_sent) = '2014/11/10'

using PhpMyAdmin, running this query:

Showing rows 0 - 247 (248 total, Query took 30.1080 seconds.)

that is a long time when this is executed on the site's homepage.

Any suggestions on how I can optimize this? Or is the server really slow?

The snapshots table has over 45K rows.

The EXPLAIN output: 在此处输入图片说明

Crazy find! When comparing the ROWS and SIZE between shared hosting and dedicated hosting of the same database and table.

Shared: 1,023,459 records @ 1.8GiB Dedicated: 43,916 records @ 4.5GiB

Why is there a discrepancy?

You are applying the function date() to every row, which is costly.

Instead, make the comparison in a way that doesn't require any conversion function, like this:

WHERE a.date_sent between '2014/11/10 00:00:00' and '2014/11/10 23:59:59'

And make sure you have an index defined on that column, and the foreign key column of the joined table.

Thanks All... Seems like the performance issue is not the query... I've optimized the query based on the suggestions above, and have not seen much improvement.

I've since moved to another hosting service and noticed a vast improvement.

The problem with your query is that it makes it quite hard for the database optimizer to apply its optimization strategies (eg indexes) because of the DATE() function being part of the where part of the query. However, a good database engine may be able to provide a speed up if the query is repeated completely unchanged.

Besides the general design recommendation to save date and time separately into different database columns (which probably would be the better way to proceed), there is an idea presented in this answer https://stackoverflow.com/a/95256/3911010 how to avoid the inefficient usage of DATE in the query.

A few things

Make your tables match. One uses a big int. The other an int. Use the same

Second remove the date function and compare to yyyy-mm-dd

Index the snapshots. Brand_I'd column to help with the join

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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