sql - Postgresql 不同计数提高性能

标签 sql postgresql count

我在 Google Cloud SQL 上有一个数据库。它包含一个简单的表格,如下所示:

url_id user_id

url_id 是一个包含整数的字符串,user_id 是一个 14 个字符的字符串。 我在 url_id 上有一个索引:

CREATE INDEX index_test ON table1 (url_id);

我想要运行的请求是获取具有不在给定 ID 列表中的 url_id 的不同 user_id 的数量。我这样做:

 SET work_mem='4GB';
 select count(*) from (select distinct afficheW from table1 where url_id != '1880' and url_id != '2022' and url_id != '1963' and url_id != '11' and url_id != '32893' and url_id != '19' ) t ;

结果:

 count  
---------
 1242298
(1 row)

Time: 2118,917 ms

该表包含 180 万行。 有没有办法可以让这种类型的请求更快?

最佳答案

尝试将其写为:

select count(distinct afficheW)
from table1
where url_id not in (1800, 2022, 1963, 11, 32892, 19);

(这假设 url_id 实际上是一个数字,而不是字符串。)

然后在 table1(url_id, affichew) 上添加索引。

也就是说,在两秒内从表中计数超过一百万个项目并不是那么糟糕。

关于sql - Postgresql 不同计数提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63454435/

相关文章:

postgresql - 使用 postgres 存储时删除 Graphite 中的系列?

php - JOIN Many table while GROUP BY and COUNT GROUP BY row in MySQL

SQL COUNT 一个值出现了多少次

sql - 使用 ARRAY_AGG 获取列中的第一个非 NULL 值是否浪费?

sql - 与调用整行相比,SQL 查询受限时的性能优势?

sql - 根据列中的重复项选择行

mysql - 将值与 where 子句中的串联字段进行比较

sql - Postgres 大于或空

mysql - SELECT,第二个表中的 2 个计数,第三个表中的 RIGHT JOIN

php - 每次给定时间插入一行,否则更新前一行(Postgresql、PHP)