简体   繁体   English

php如何在分页中正确使用COUNT?

[英]How to use COUNT properly with pagination in php?

This is how I have my current query setup: 这就是我当前的查询设置的方式:

SELECT * , (    
SELECT COUNT( * ) 
FROM paintings
WHERE id > 4000
) AS total
FROM paintings
WHERE id > 4000
LIMIT 0 , 30

Everything works fine if I separate the queries but if I keep it like this the pagination shows 1 id missing at the end of the page. 如果我分开查询,一切都会很好,但是如果我这样保留它,则分页将在页面末尾显示1个ID。

What would be a better option for selecting count that doesn't return on each row but for the whole? 选择不对每一行返回但对整个行返回的计数的更好的选择是什么?

Ex: this is what I currently get if I pass that in mysql: 例如:如果我在mysql中通过,这就是我目前得到的:

> +--------+------------+--------+
> |  id    | title      | count  |
> +--------+------------+--------+
> | 2345   | water      |   25   | 
> | 2346   | bread      |   25   | 
> | 2347   | coke       |   25   | 
> | 2348   | beer       |   25   | 
> | 2349   | oranges    |   25   | 
> +--------+------------+--------+

Cheers! 干杯!

There isn't, in way you did it. 没有,您做的方式。 Just run 2 queries 只需运行2个查询

SELECT 
     *
FROM 
     paintings
WHERE 
     id >4000
LIMIT 
     0 , 30;

SELECT 
    COUNT( * ) as total
FROM 
    paintings
WHERE 
    id >4000

Addition to what genesis posted. 除了创世记。 Still 2 queries but a little cleaner: 仍然有2个查询,但更简洁:

# The main query
SELECT SQL_CALC_FOUND_ROWS * FROM paintings
WHERE id > 4000
LIMIT 0, 30;

# And after get the total
SELECT FOUND_ROWS() AS total;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM