postgresql COUNT(DISTINCT ...) 很慢 [英] postgresql COUNT(DISTINCT ...) very slow

查看:172
本文介绍了postgresql COUNT(DISTINCT ...) 很慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的 SQL 查询:

I have a very simple SQL query:

SELECT COUNT(DISTINCT x) FROM table;

我的表有大约 150 万行.这个查询运行得很慢;大约需要 7.5 秒,相比之下

My table has about 1.5 million rows. This query is running pretty slowly; it takes about 7.5s, compared to

 SELECT COUNT(x) FROM table;

大约需要 435 毫秒.有什么方法可以更改我的查询以提高性能吗?我尝试过分组并进行常规计数,以及在 x 上放置索引;两者具有相同的 7.5 秒执行时间.

which takes about 435ms. Is there any way to change my query to improve performance? I've tried grouping and doing a regular count, as well as putting an index on x; both have the same 7.5s execution time.

推荐答案

你可以使用这个:

SELECT COUNT(*) FROM (SELECT DISTINCT column_name FROM table_name) AS temp;

这比:

COUNT(DISTINCT column_name)

这篇关于postgresql COUNT(DISTINCT ...) 很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆