我在 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/