oracle12c,sql,count(*)和sum()的区别

oracle12c,sql,difference between count(*) and sum()

告诉我sql1和sql2的区别:

sql1:

select count(1)
from table_1 a
inner join table_2 b on a.key = b.key where a.id in (
  select id from table_1 group by id having count(1) > 1
) 

sql2:

select sum(a) from (
  select count(1) as a
  from table_1 a
  inner join table_2 b on a.key = b.key group by a.id having count(1) > 1
)

为什么输出不一样?

当您使用 count(*) 时,您计算所有行。 SUM() 函数是一个聚合函数,它 returns 一组值中所有值或不同值的总和。

查询甚至都不相似。他们非常不同。让我们检查第一个:

select count(1)
from table_1 a
inner join table_2 b
on a.key = b.key 
where a.id in (
  select id from table_1 group by id having count(1) > 1
) ;

您首先进行内部联接:

select count(1) 
from table_1 a 
inner join table_2 b 
on a.key = b.key

这种情况下可以使用count(1), count(id), count(*),它们是等价的。您正在计算两个 table 中的 共同元素 :那些具有共同关键字段的元素。

之后,您将执行此操作:

where a.id in (
      select id from table_1 group by id having count(1) > 1
    ) 

换句话说,table_1的每个“id”必须在table_1table中至少出现两次。

最后,您正在这样做:

select count(1)

换句话说,计算那些元素。所以,翻译成英文你已经这样做了:

  1. 获取table_1的每条记录,并与table_2的记录配对,获取匹配
  2. 的记录
  3. 对于上面的结果,只过滤掉table_1的id出现次数超过1次的元素
  4. 计算那个结果

让我们看看第二个查询会发生什么:

select sum(a) from (
  select count(1) as a
  from table_1 a
  inner join table_2 b 
  on a.key = b.key 
  group by a.id 
  having count(1) > 1
);

您正在进行相同的内部联接:

  select count(1) as a
  from table_1 a
  inner join table_2 b 
  on a.key = b.key 

但是,您是按 table:

的 ID 对其进行分组
  group by a.id 

然后只过滤掉那些出现不止一次的元素:

  having count(1) > 1

到目前为止的结果是一组记录,它们在两个 table 中具有共同的关键字段,但按 id 分组:这意味着 只有那些字段位于table_b 中的 leas 两次是此 join 的输出。之后,您按 id 分组,将这些结果折叠到 table_1.id 字段中并计算结果。我认为很少有记录符合这个严格的标准。

最后,您对所有这些集合求和。