【发布时间】:2012-09-07 22:08:06
【问题描述】:
在 Sql select 语句中获取 Count 作为字段的最佳方法
我有 2 个表:Person 和 Orders
人
Id Name Age
1 name1 1
2 name2 2
订购
Id Amount PersonId
1 30 1
2 40 2
3 30 2
4 40 2
5 30 1
6 40 2
7 30 1
8 40 2
我想要用户详细信息以及订单总数,因此为此我有 2 个解决方案:
1. select p.Name,p.Age,(select count(1) form orders o where o.personId= p.Id as cntVal
from Person p
2. select p.Name,p.Age,cntVal
from Person p
inner join (select personId,count(1) as cntVal from orders o group by PersonId) cnt
on cnt.personId=p.Id
我们在 Person 表中有大约 200K 条记录,在 Order 表中有 15K 条记录。 我想知道哪种方法更好? 或者你可以建议我更快的查询
【问题讨论】:
-
应该在速度上没有差异(特别是如果您将第二个内部查询修复为按 personId 分组)。此外,您可以使用 count(*) 来提高可读性。
-
Arvo - 出于性能原因,count(1) 优于 count(*)
-
@VeeBee:完全是垃圾:stackoverflow.com/questions/1221559/count-vs-count1/…
-
@VeeBee 这不是真的。 Please check this answer out.
-
yashpal - 2 比 1 更有效,但您可以通过在外部使用 Group By 进一步改进 2(请参阅下面保罗的回答)
标签: sql sql-server sql-server-2008 tsql