我有一个查询的效果
SELECT t3.id, a,bunch,of,other,stuff FROM t1, t2, t3
WHERE (associate t1,t2, and t3 with each other)
GROUP BY t3.id
LIMIT 10,20
Run Code Online (Sandbox Code Playgroud)
我想知道很多总行,这个查询将返回没有LIMIT(所以我可以显示分页信息).
通常,我会使用此查询:
SELECT COUNT(t3.id) FROM t1, t2, t3
WHERE (associate t1,t2, and t3 with each other)
GROUP BY t3.id
Run Code Online (Sandbox Code Playgroud)
但是,GROUP BY更改了COUNT的含义,而是获得了一组行,表示每个组中唯一的t3.id值的数量.
当我使用GROUP BY时,有没有办法计算总行数?我想避免执行整个查询并只计算行数,因为我只需要行的子集,因为值是分页的.我正在使用MySQL 5,但我认为这非常通用.
Syl*_*ain 53
MySQL中有一个很好的解决方案.
在关键字SELECT之后添加关键字SQL_CALC_FOUND_ROWS:
SELECT SQL_CALC_FOUND_ROWS t3.id, a,bunch,of,other,stuff FROM t1, t2, t3
WHERE (associate t1,t2, and t3 with each other)
GROUP BY t3.id
LIMIT 10,20
Run Code Online (Sandbox Code Playgroud)
之后,使用函数FOUND_ROWS()运行另一个查询:
SELECT FOUND_ROWS();
Run Code Online (Sandbox Code Playgroud)
它应返回没有LIMIT子句的行数.
有关更多信息,请访问此页面:http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
Tom*_*m H 50
"一堆其他东西"都聚集在一起吗?我假设是因为你的GROUP BY只有t3.id. 如果是这种情况那么这应该工作:
SELECT
COUNT(DISTINCT t3.id)
FROM...
Run Code Online (Sandbox Code Playgroud)
另一种选择当然是:
SELECT
COUNT(*)
FROM
(
<Your query here>
) AS SQ
Run Code Online (Sandbox Code Playgroud)
我不使用MySQL,所以我不知道这些查询是否可以在那里工作.
Sil*_*oon 12
使用子查询:
SELECT COUNT(*) FROM
(
SELECT t3.id, a,bunch,of,other,stuff FROM t1, t2, t3
WHERE (associate t1,t2, and t3 with each other)
GROUP BY t3.id
)
as temp;
Run Code Online (Sandbox Code Playgroud)
所以temp包含行数.
Bil*_*win 11
您正在使用MySQL,因此您可以使用它们的功能来完成此操作.
SELECT SQL_CALC_FOUND_ROWS t3.id, a,bunch,of,other,stuff
FROM t1, t2, t3
WHERE (associate t1,t2, and t3 with each other)
GROUP BY t3.id
LIMIT 10,20;
SELECT FOUND_ROWS(); -- for most recent query
Run Code Online (Sandbox Code Playgroud)
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
| 归档时间: |
|
| 查看次数: |
92184 次 |
| 最近记录: |