如何计算MySQL查询返回的总结果的限制?

时间:2012-05-09 23:20:15

标签: php mysql database search

我使用以下查询从MySQL数据库中获取结果:

$query =  $this->db->query("
    SELECT * FROM results r 
    INNER JOIN categories c on r.id = c.result_id 
    INNER JOIN tags t on r.id = t.result_id 
    WHERE c.name in ('$purpose', '$prop_type', '$loan_type')
    $tag_string
    AND ( r.scope = 'all' OR r.scope = '$subdomain' )
    GROUP BY r.id
    HAVING COUNT(c.c_id) = 3
    ORDER BY r.usefulness DESC
    LIMIT 10 OFFSET $offset
");

返回的结果可能是500+

如果没有限制,我如何计算此查询将返回的总行数,以便我可以将其显示给用户?

2 个答案:

答案 0 :(得分:4)

SQL_CALC_FOUND_ROWS和“SELECT FOUND_ROWS()”就是你想要的:

http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows

答案 1 :(得分:3)

这很简单,只需使用select count(*) from ...代替select * from ...

如果您想在同一个查询中完成所有操作,请在此处获得答案:

How to count and limit record in a single query in MYSQL?

另外一个SELECT FOUND_ROWS();就是答案。