开发者

Help optimizing an SQL Query

I am having noticing some performance issues on my MySQL Server. The slow query log is showing four queries which are causing the issue, taking around 10 seconds to run each query. I'm wondering if there is a more efficient way of running the query.

The table I am selecting from has around 13,000 rows, and is structured like:

id  p   year    time            b      o           type
1   dec 10  2010-12-02 12:34:27 1000    1000        cape
2   jan 10  2010-12-02 12:34:27 1000    1000        cape
3   feb 10  2010-12-02 12:34:27 1000    1000        cape
4   q1  10  2010-12-02 12:34:27 1000    1000        cape
5   q2  10  2010-12-02 12:34:27 1000    1000        cape
6   q3  10  2010-12-02 12:34:27 1000    1000        cape
7   q4  10  2010-12-02 12:34:27 1000    1000        cape
8   11  10  2010-12-02 12:34:27 1000    1000        cape
9   12  10  2010-12-02 12:34:27 1000    1000        cape
10  dec 10  2010-12-02 12:34:27 1000    1000        pmx
11  jan 10  2010-12-02 12:34:27 1000    1000        pmx
12  feb 10  2010-12-02 12:34:27 1000    1000        pmx
13  q1  10  2010-12-02 12:34:27 1000    1000        pmx
14  q2  10  2010-12-02 12:34:27 1000    1000开发者_Python百科        pmx
15  q3  10  2010-12-02 12:34:27 1000    1000        pmx
16  q4  10  2010-12-02 12:34:27 1000    1000        pmx

I run four queries - one for each type, which select each p and order by time. This data is displayed on the front end of the website through four tables.

The queries that are slow are:

SELECT type,id,p,time,b,o
FROM zz
WHERE id = (SELECT MAX(id) FROM zz AS f
            WHERE f.p = zz.p
            AND type = 'pmx')
AND TYPE = 'pmx';

(then the same for three other types)

Does anyone have any tips for improving the actual query?

Thanks


How about something like

SELECT  zz.type,
        zz.id,
        zz.p,
        zz.time,
        zz.b,
        zz.o
FROM    zz INNER JOIN
        (
            SELECT  type,
                    MAX(id) MaxID
            FROM    zz
            WHERE   type IN ('1','2','3','4')
            GROUP BY type
        ) m ON  zz.type = m.type
            AND zz.ID = m.MaxID

Where ('1','2','3','4') are the four types in question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜