SELECT 语句后需要行计数:最佳 SQL 方法是什么?
我试图从单个表中选择一列(无连接),并且我需要行数的计数,最好是在开始检索行之前。 我采用了两种方法来提供我需要的信息。
方法 1:
SELECT COUNT( my_table.my_col ) AS row_count
FROM my_table
WHERE my_table.foo = 'bar'
然后
SELECT my_table.my_col
FROM my_table
WHERE my_table.foo = 'bar'
或者方法 2
SELECT my_table.my_col, ( SELECT COUNT ( my_table.my_col )
FROM my_table
WHERE my_table.foo = 'bar' ) AS row_count
FROM my_table
WHERE my_table.foo = 'bar'
我这样做是因为我的 SQL 驱动程序 (SQL Native Client 9.0) 不允许我在 SELECT 语句上使用 SQLRowCount,但我需要了解结果中的行数,以便在向数组分配信息之前分配数组。 不幸的是,在我的程序的这个区域中不可以选择使用动态分配的容器。
我担心可能会发生以下情况:
- 发生 SELECT for count 发生
- 另一条指令,添加或删除行
- 发生 SELECT for data 突然数组大小错误。
- 在最糟糕的情况下,这将尝试写入超出数组限制的数据并使我的程序崩溃。
方法 2 是否禁止此问题?
另外,这两种方法中的一种会更快吗? 如果有,是哪一个?
最后,我是否应该考虑更好的方法(也许是一种指示驱动程序使用 SQLRowCount 返回 SELECT 结果中的行数的方法?)
对于那些询问的人,我正在使用 Native C++ 和上述 SQL 驱动程序(前提是由微软开发。)
I'm trying to select a column from a single table (no joins) and I need the count of the number of rows, ideally before I begin retrieving the rows. I have come to two approaches that provide the information I need.
Approach 1:
SELECT COUNT( my_table.my_col ) AS row_count
FROM my_table
WHERE my_table.foo = 'bar'
Then
SELECT my_table.my_col
FROM my_table
WHERE my_table.foo = 'bar'
Or Approach 2
SELECT my_table.my_col, ( SELECT COUNT ( my_table.my_col )
FROM my_table
WHERE my_table.foo = 'bar' ) AS row_count
FROM my_table
WHERE my_table.foo = 'bar'
I am doing this because my SQL driver (SQL Native Client 9.0) does not allow me to use SQLRowCount on a SELECT statement but I need to know the number of rows in my result in order to allocate an array before assigning information to it. The use of a dynamically allocated container is, unfortunately, not an option in this area of my program.
I am concerned that the following scenario might occur:
- SELECT for count occurs
- Another instruction occurs, adding or removing a row
- SELECT for data occurs and suddenly the array is the wrong size.
-In the worse case, this will attempt to write data beyond the arrays limits and crash my program.
Does Approach 2 prohibit this issue?
Also, Will one of the two approaches be faster? If so, which?
Finally, is there a better approach that I should consider (perhaps a way to instruct the driver to return the number of rows in a SELECT result using SQLRowCount?)
For those that asked, I am using Native C++ with the aforementioned SQL driver (provided by Microsoft.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
如果您使用的是 SQL Server,则在查询后您可以选择 @@RowCount 函数(或者,如果您的结果集可能有超过 20 亿行,请使用 RowCount_Big() 函数)。 这将返回上一个语句选择的行数或受插入/更新/删除语句影响的行数。
或者,如果您希望将行计数包含在与方法 #2 类似的发送结果中,您可以使用 OVER 子句。
使用 OVER 子句比使用子查询获取行数具有更好的性能。 使用 @@RowCount 将具有最佳性能,因为 select @@RowCount 语句不会有任何查询成本
更新响应评论:我给出的示例将给出分区中的行数 - 在本例中定义通过“PARTITION BY my_table.foo”。 每行中列的值是与 my_table.foo 值相同的行数。 由于您的示例查询具有子句“WHERE my_table.foo = 'bar'”,因此结果集中的所有行都将具有相同的 my_table.foo 值,因此该列中的值对于所有行都将相同并且相等(在在本例中)这是查询中的行数。
下面是一个更好/更简单的示例,说明如何在每行中包含一列,该列是结果集中的总行数。 只需删除可选的 Partition By 子句即可。
If you're using SQL Server, after your query you can select the @@RowCount function (or if your result set might have more than 2 billion rows use the RowCount_Big() function). This will return the number of rows selected by the previous statement or number of rows affected by an insert/update/delete statement.
Or if you want to row count included in the result sent similar to Approach #2, you can use the the OVER clause.
Using the OVER clause will have much better performance than using a subquery to get the row count. Using the @@RowCount will have the best performance because the there won't be any query cost for the select @@RowCount statement
Update in response to comment: The example I gave would give the # of rows in partition - defined in this case by "PARTITION BY my_table.foo". The value of the column in each row is the # of rows with the same value of my_table.foo. Since your example query had the clause "WHERE my_table.foo = 'bar'", all rows in the resultset will have the same value of my_table.foo and therefore the value in the column will be the same for all rows and equal (in this case) this the # of rows in the query.
Here is a better/simpler example of how to include a column in each row that is the total # of rows in the resultset. Simply remove the optional Partition By clause.
只有两种方法可以 100% 确定
COUNT(*)
和实际查询会给出一致的结果:COUNT(*)
与查询结合起来,如下所示在你的方法2中。我推荐你在示例中显示的形式,而不是kogus评论中显示的相关子查询形式。SNAPSHOT
或SERIALIZABLE
隔离级别启动事务后,使用两个查询,如方法 1 中所示。使用这些隔离级别之一很重要,因为任何其他隔离级别都允许其他客户端创建的新行在当前事务中可见。 阅读有关
设置事务隔离
的 MSDN 文档更多细节。There are only two ways to be 100% certain that the
COUNT(*)
and the actual query will give consistent results:COUNT(*)
with the query, as in your Approach 2. I recommend the form you show in your example, not the correlated subquery form shown in the comment from kogus.SNAPSHOT
orSERIALIZABLE
isolation level.Using one of those isolation levels is important because any other isolation level allows new rows created by other clients to become visible in your current transaction. Read the MSDN documentation on
SET TRANSACTION ISOLATION
for more details.方法 2 将始终返回与您的结果集匹配的计数。
不过,我建议您将子查询链接到外部查询,以保证计数条件与数据集条件匹配。
Approach 2 will always return a count that matches your result set.
I suggest you link the sub-query to your outer query though, to guarantee that the condition on your count matches the condition on the dataset.
如果您担心满足条件的行数可能会在执行查询和检索结果后的几毫秒内发生变化,您可以/应该在事务内执行查询:
这将始终返回正确的值。
此外,如果您使用的是 SQL Server,则可以使用 @@ROWCOUNT 获取受最后一条语句影响的行数,并将 real 查询的输出重定向到临时表或表变量,因此您可以完全退回所有内容,无需进行交易:
If you're concerned the number of rows that meet the condition may change in the few milliseconds since execution of the query and retrieval of results, you could/should execute the queries inside a transaction:
This would return the correct values, always.
Furthermore, if you're using SQL Server, you can use @@ROWCOUNT to get the number of rows affected by last statement, and redirect the output of real query to a temp table or table variable, so you can return everything altogether, and no need of a transaction:
这里有一些想法:
Here are some ideas:
如果您确实担心行计数会在 select 计数和 select 语句之间发生变化,为什么不先将行选择到临时表中呢? 这样,您就知道你们会保持同步。
If you are really concerned that your row count will change between the select count and the select statement, why not select your rows into a temp table first? That way, you know you will be in sync.
为什么不将结果放入向量中? 这样您就不必事先知道尺寸。
Why don't you put your results into a vector? That way you don't have to know the size before hand.
您可能需要考虑一种更好的模式来处理此类数据。
没有自卫的 SQL 驱动程序会在返回行之前告诉您查询将返回多少行,因为答案可能会改变(除非您使用事务,这会产生自己的问题。)
行数不会改变 -谷歌搜索 ACID 和 SQL。
You might want to think about a better pattern for dealing with data of this type.
No self-prespecting SQL driver will tell you how many rows your query will return before returning the rows, because the answer might change (unless you use a Transaction, which creates problems of its own.)
The number of rows won't change - google for ACID and SQL.
只是添加这个,因为这是谷歌针对这个问题的最高结果。
在 sqlite 中我用它来获取行数。
Just to add this because this is the top result in google for this question.
In sqlite I used this to get the rowcount.