我想要的是向DB发送请求:
1计算所有行
2返回10行
SELECT count( * ) AS 'total'
FROM stuff
WHERE usr = '65'
LIMIT 10
所以它应该返回10个结果PLUS'total'和所有行的数量。 到目前为止,它仅返回计算的行数....
答案 0 :(得分:2)
你需要将两个问题分开,然后重新组合它们:
SELECT s.col1, s.col2, s.col3, x.total
FROM `stuff` s
CROSS JOIN
(
SELECT count(*) AS total
FROM `stuff`
WHERE `usr` = '65'
) x
WHERE s.`usr` = '65'
LIMIT 10;
Fiddle here
像SqlServer和Oracle这样的RDBM允许CTE,它允许你干掉重复的select ... where
。 MySql here
答案 1 :(得分:2)
-- count records first
SET @total = (
SELECT count( * ) AS 'total'
FROM `stuff`
WHERE `usr` = '65'
);
-- then, select your ten records and include the total from previous operation
SELECT *, @total
FROM `stuff`
WHERE `usr` = '65'
LIMIT 10
答案 2 :(得分:0)
如果您想要计算所有行并将结果限制为10,那么您可以通过以下方式执行此操作
SELECT SQL_CALC_FOUND_ROWS * FROM `stuff` WHERE `usr` = '65' LIMIT 10
SELECT FOUND_ROWS();