如何在PHP中使用COUNT正确使用COUNT?

时间:2011-09-17 16:12:49

标签: php mysql pagination

这就是我当前查询设置的方式:

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

如果我将查询分开,一切正常,但如果我保持这样,分页会在页面末尾显示1个ID。

选择不在每一行但不是全部返回的计数会有什么更好的选择?

例如:如果我在mysql中传递它,这是我目前得到的:

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

干杯!

2 个答案:

答案 0 :(得分:3)

没有,你做到了。只需运行2个查询

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

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

答案 1 :(得分:3)

除了发表的内容之外。仍有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;