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-2开发者_开发知识库4, 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
精彩评论