简体   繁体   中英

mysql optimize query for paging

pls can anybody help me width this query? I cannot find solution for it.

SELECT *,p.cat_id, cat_name FROM ( SELECT cat_id FROM categories ORDER BY cat_id LIMIT 700000, 10 ) o JOIN categories p ON p.cat_id = o.cat_id ORDER BY p.cat_id

It is very fast on table with 800 000 records, but what I need is to sort data with order by clause and where claue,too - for paging. If I use order by it si very slow or result is not ordered correctly>

SELECT *, p.cat_id, cat_name FROM(
    SELECT  cat_id
    FROM    categories
    LIMIT 700000, 10
    ) o JOIN    categories p
ON      p.cat_id = o.cat_id
ORDER BY p.cat_name

page 1
LIMIT 700000,5:
 id      name
 12525525   car
 15155151   carpet
 1521512i   zone

page 2
LIMIT 700005,5
 id        name
12525525   carefull
15155151   excellent
52151222   drive

I need result:

page 1 car 
carpet
drive 
excellent ... etc.


f.e. , this is very slow ofcourse >
SELECT *, p.cat_id, cat_name 
FROM    (
        SELECT  cat_id
        FROM    categories
        **ORDER BY cat_name**
        LIMIT 700000, 10
        ) o
JOIN    categories p
ON      p.cat_id = o.cat_id
ORDER BY p.cat_name

primary key cat_id, autoincrement I have indexes on fields in table

Many thanks for help or some ideas

You didn't need to JOIN the same table, and you have to do the ORDER BY in an inner query to be ordered correctly with the WHWRE clause in the outer one:

 SET @rownum = 0;
 SELECT t.*, t.rank as TableRank
 FROM
 (
    SELECT *,  (@rownum := @rownum + 1) as rank
    FROM categories c 
    ORDER BY c.cat_name
 ) t 
 WHERE rank BETWEEN ((@PageNum - 1) * @PageSize + 1)
 AND (@PageNum * @PageSize)

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