distinct vs group by 哪个更好

distinct vs group by which is better

我们都参考最简单的情况:

select id from mytbl 
group by id

select distinct id from mytbl

正如我们所知,它们生成相同的查询计划,这些计划已在某些项目中反复提及,例如 Which is better: Distinct or Group By

然而在hive中,前者只有一个reduce任务,而后者有很多。

根据实验,我发现 GROUP BY 比 DISTINCT 快 10+ 倍

它们是不同的。

所以我学到的是:

GROUP-BY 反正不比 DISTINCT 差,有时还好。

我想知道:

1。如果这个结论成立。

2。如果为真,我将考虑将 DISTINCT 作为一种逻辑上方便的方法,但为什么 DISTINCT 不采用 GROUP-BY 的更好实现方式?

3。如果是false,我很想知道它在大数据情况下的正确用法

非常感谢!!:)

你的经历很有趣。我还没有看到 distinctgroup by 的单一减速器效果。也许这两种构造之间的优化器存在一些细微差别。

Hive 中的一个 "famous" 示例是:

select count(distinct id)
from mytbl;

对比

select count(*)
from (select distinct id
      from mytbl
     ) t;

前者只用一个reducer,后者并行运行。我在我的经验中已经看到了这一点,并且对其进行了记录和讨论(例如,在本 presentation 中的幻灯片 26 和 27 上)。所以,distinct绝对可以利用并行性。

我想随着 Hive 的成熟,这些问题会得到解决。然而,具有讽刺意味的是,Postgres 与 COUNT(DISTINCT) 有类似的性能问题,尽管我认为根本原因有点不同。

我执行相同的任务并通过 postgres 命令进行分析。 对于不同的查询:explain (analyze) select distinct product_id, size from logistic.product_stock where status = 'STOCK' 我得到:

HashAggregate  (cost=2166.24..2232.35 rows=6611 width=23) (actual time=46.417..47.104 rows=3770 loops=1)
   Group Key: product_id, size
   Batches: 1  Memory Usage: 721kB
   ->  Seq Scan on product_stock  (cost=0.00..2050.57 rows=23133 width=23) (actual time=0.144..39.954 rows=22357 loops=1)
         Filter: ((status)::text = 'STOCK'::text)
         Rows Removed by Filter: 44930
 Planning Time: 0.126 ms
 Execution Time: 47.517 ms

对于分组查询 explain (analyze) select product_id, size from logistic.product_stock where status = 'STOCK' group by product_id, size 我得到下一个:

HashAggregate  (cost=2166.24..2232.35 rows=6611 width=23) (actual time=40.519..41.273 rows=3775 loops=1)
   Group Key: product_id, size
   Batches: 1  Memory Usage: 721kB
   ->  Seq Scan on product_stock  (cost=0.00..2050.57 rows=23133 width=23) (actual time=0.053..34.159 rows=22362 loops=1)
         Filter: ((status)::text = 'STOCK'::text)
         Rows Removed by Filter: 44930
 Planning Time: 0.802 ms
 Execution Time: 41.768 ms

正如我们所见:两种情况下的步骤相同。 Seq 扫描 -> 组键。

答案:无论您选择什么查询

PS。时间取决于缓存。