13

I'm trying to create a simple image gallery, showing 16 images per page. I'm using LIMIT 16 to display the correct amount on the page, but if there are more than 16 rows, I want to have links at the bottom, allowing the user to navigate to the next page.

I know I could achieve the desired result by removing the limit and simply using a loop to display the first 16 items, but this would be inefficient. Obviously, COUNTING the number of rows would always = 16.

$sql .= "posts p, images im, postimages pi WHERE
    i.active = 1 
    AND pi.post_id = p.id
    AND pi.image_id = im.image_id 
    ORDER BY created_at LIMIT 16";

Can anyone suggest a more efficient way of doing it?

Thanks

4

5 回答 5

29

MySQL

SELECT  SQL_CALC_FOUND_ROWS
        *
FROM    posts p, images im, postimages pi
WHERE   i.active = 1 
        AND pi.post_id = p.id
        AND pi.image_id = im.image_id 
ORDER BY
        created_at
LIMIT 16;

SELECT  FOUND_ROWS();

第一个查询将返回16行,第二个查询将返回在第一个查询中没有LIMIT子句的情况下将返回的行数。

您可以使用它来决定是否显示“下一个”链接。

于 2009-07-14T15:07:57.407 回答
4

Run a separate query with no limit that only returns the count.

于 2009-07-14T15:02:53.233 回答
3

Are you trying to fully paginate, or just have this page and next page? If it's the latter you can simply LIMIT 17 and count the rows of the result. If you get 17 you need to paginate.

于 2009-07-14T15:02:31.237 回答
1

除了用于获取其他人提到的计数的单独查询之外,您还需要抵消您所在页面的结果。

$sql .= "posts p, images im, postimages pi WHERE
    i.active = 1 
    AND pi.post_id = p.id
    AND pi.image_id = im.image_id 
    ORDER BY created_at 
    LIMIT ". ($page - 1) * $pagesize .", ". $pagesize;

有关 SQL 注入的正常警告将适用于此处。

于 2009-07-14T15:07:32.820 回答
0

use two queries, where one is your query and the other is:

SELECT COUNT(primary_key) FROM ... WHERE...
于 2009-07-14T15:02:53.267 回答