SQL 查询优化/做事的正确技术(SQL 服务器)

SQL Query Optimization / Right Technique to do the thing (SQL Server)

我要数数。 SQL 动态(用户输入)

查询返回的记录数

所以我执行以下操作

select count(*) from (user query);

如何优化这个?

例如

select count(*) from (select name,unitprice,brand from product);

如果产品 table 有 > 100,000 条记录。

NOTE: the user query can have a group by as well as an order by.

我假设您需要 运行 用户查询,但还需要其他内容的计数。 @@ROWCOUNT 是实现此目的的内置方法:

SELECT name, unitprice, brand, etc
FROM product
GROUP BY name, unitprice, brand, etc
ORDER BY name, etc;

SELECT @@ROWCOUNT;

根据您要对计数执行的操作,您可能希望将它放在一个变量中以便稍后引用它,因为 @@ROWCOUNT 仅适用于最后执行的查询:

DECLARE @ROWCOUNT int;
SELECT yourQuery;
SELECT @ROWCOUNT = @@ROWCOUNT;

SELECT @ROWCOUNT;