简体   繁体   中英

SQL query, specify which top results?

I have a SQL query that current returns the top 50 rows from a query.

LEFT JOIN users u
ON c.id = u.id
ORDER BY c.date DESC LIMIT 50;

I would like to change the LIMIT 50 to be dynamic, so I could specify results 1-24, 25-50, etc. How can I change LIMIT 50 to work this way?

Thanks!

ORDER BY c.date DESC LIMIT 0, 25;

ORDER BY c.date DESC LIMIT 25, 25;

ORDER BY c.date DESC LIMIT 75, 25;


$page = 0; // 1, 2, 3
$perPage = 25;

$query = ' ... ORDER BY c.date DESC LIMIT ' . ( $page * $perPage ) . ', ' . $perPage;

like this

LIMIT 0,25

LIMIT 25,25

or

LIMIT 25 OFFSET 0

LIMIT 25 OFFSET 25

Syntax is:

[LIMIT {[offset,] row_count | row_count OFFSET offset}]

See http://dev.mysql.com/doc/refman/5.1/en/select.html

You can't. You can only retrieve a consecutive range of rows using LIMIT .

However, you can merge two results together in a UNION :

(
    SELECT
    ...
    LEFT JOIN users u
    ON c.id = u.id
    ORDER BY c.date DESC LIMIT 1,25;
)
UNION
(
    SELECT
    ...
    LEFT JOIN users u
    ON c.id = u.id
    ORDER BY c.date DESC LIMIT 25,26;
)

If you dont like that comma, you can use the syntax

LIMIT 0 OFFSET 25
LIMIT 25 OFFSET 25

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