【问题标题】:Best way to get Count as field in Sql select statement在 Sql select 语句中获取 Count 作为字段的最佳方法
【发布时间】: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 这不是真的。 Please check this answer out.
  • yashpal - 2 比 1 更有效,但您可以通过在外部使用 Group By 进一步改进 2(请参阅下面保罗的回答)

标签: sql sql-server sql-server-2008 tsql


【解决方案1】:

我错过了什么吗?

select  p.name, p.age, count(o.OrderId)
from    Person p join Orders o on p.PersonId = o.PersonId
group by p.name, p.age

【讨论】:

    【解决方案2】:

    如果您只关心效率和速度,我建议您使用 SQL Profiler 并查看哪个选项生成最快的结果,同时消耗最少的读取和资源。

    您还有其他选择:

    Select  
       p.Name, 
       p.Age, 
       Count(*) as OrderCount
    From  Person p 
       Join Orders o on p.PersonId = o.PersonId
    Group By p.Name, p.Age
    

    测试所有这些,看看哪个最好。

    【讨论】:

      【解决方案3】:

      这是另一种选择 - 这将是我的首选。

      select p.Name,p.Age, count(orderID)
      from 
          Person p 
      inner join 
          Orders o
              on p.Id = o.personId
      group by p.id, p.Name, p.Age
      

      如果您希望将未下订单的人也计算在内,请将内连接更改为左连接

      【讨论】:

      • 我对这种方法唯一担心的是person 中是否还有更多列,OP 也希望检索这些列。但是,是的,从提出的问题来看,这似乎是要走的路,其他大多数事情都太复杂了。
      • 我的实际问题更复杂,我有几个其他表参与查询,所以我们不能使用分组。例如用户支付的总金额、信用卡支付次数、借记卡支付次数等。我有大约 15 个表在加入,所以它不适合我。
      • 在这种情况下,我认为您需要使用 2 中概述的子查询。为它创建一个视图可能会有所帮助。
      猜你喜欢
      • 2012-08-12
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 2016-05-21
      • 2012-09-22
      • 1970-01-01
      相关资源
      最近更新 更多