简体   繁体   English

哪个更快,为每个类别获取Count()或从数据集查询以及如何执行

[英]Which is Faster, Getting Count() for each category or querying from Dataset and How to do it

I am currently trying to get number of articles present in each category(specific ID) to show it beside the category name. 我目前正在尝试获取每个类别(特定ID)中存在的文章数,以将其显示在类别名称旁边。 This is how it looks like 看起来像这样 分类

Now I am trying to assign the label control with count to respective categories. 现在,我尝试将带有计数的标签控件分配给各个类别。 I have two options, by running below select query 6 times for each category and assign it. 我有两个选择,通过在每个类别下面运行select查询6次并分配它。

Select Count(Cat) from tbl_blg where Cat ='1' //should do so for all the 6 ID's 

Or 要么

SqlCommand cmdcount = new SqlCommand("SELECT Cat from tbl_blg",cnn);
        SqlDataAdapter dacount = new SqlDataAdapter(cmdcount);
        dacount.Fill(dscount);

        int scount = Convert.ToInt32(dscount.Tables["tbl_blg"].AsEnumerable().Count(r => r.Field<int>("Cat") == 1));

Now First one will be tedious(6 queries at one go), I believe, correct me if am wrong. 现在,我相信第一个很乏味(一次查询6个问题),如果错了,请纠正我。

Second one will be better(only one query and assigning it to Dataset) however the problem is it is returning null and throwing null exception... 第二个会更好(只有一个查询并将其分配给Dataset),但是问题是它返回null并引发null异常...

Which one you think is faster ? 您认为哪一个更快? if it is second option then is my code correct ? 如果这是第二选择,那么我的代码正确吗? it's returning null but should be returning 2 它返回null但应该返回2

Rewrite your second query to. 将第二个查询重写为。

SELECT COUNT(Cat) as Count, Cat FROM tbl_blg
Group by Cat

Gives you the count of how much each category is present. 给您每个类别的数量。 What you are doing now is selecting everything from that table and then do the counting. 您现在要做的是从该表中选择所有内容,然后进行计数。 By doing the group by on query level you limit how much results are being retrieved. 通过在查询级别进行分组,可以限制要检索的结果数。

The current query retrieves; 当前查询检索;

Cat1 
Cat1 
Cat1 
Cat1 
Cat2

And with group by statement you retrieve; 并通过分组语句检索;

4, Cat1
1, Cat2

Doing multiple query is basically a no-go for this situation. 对于这种情况,进行多次查询基本上是不行的。 Also EF always adds a bit of overhead on your request, so when it is performance critical you could consider using some more low-level ORM like Dapper or start using SQL/Stored procedures. 此外,EF总是会在您的请求上增加一些开销,因此,当它对性能至关重要时,您可以考虑使用一些更底层的ORM(例如Dapper)或开始使用SQL /存储过程。

You can also use a window function. 您也可以使用窗口功能。

SELECT COUNT() OVER(PARTITION BY cat ORDER BY cat) AS 'Count'
FROM tbl_blg

Also if you are going to be calling this code constantly I would highly suggest making it a stored procedure. 另外,如果您要不断调用此代码,我强烈建议将其设置为存储过程。 The benefit of a stored procedure is your sql server doesn't have to recompile the code every time. 存储过程的好处是您的sql server不必每次都重新编译代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM