通过计数过滤优化PostgreSQL查询

时间:2016-10-09 07:22:07

标签: postgresql optimization aggregate

有没有办法在PostgreSQL 9.5,9.6中优化这样的查询?

$posts = Post::select(DB::raw
('CASE
   WHEN id.PinRequestCount <> 0 THEN 5
   WHEN id.HighCallAlertCount <> 0 THEN 4
   WHEN id.HighAlertCount <> 0 THEN 3
   WHEN id.MediumCallAlertCount <> 0 THEN 2
   WHEN id.MediumAlertCount <> 0 THEN 1
END desc')
)->orderBy('id', 'DESC')->get();

所有SELECT x FROM ( SELECT x,count(x) cnt FROM very_big_table WHERE (conditions) GROUP BY x ) sub WHERE cnt > 10 条件的索引和WHERE是obvios。还有其他建议吗?

2 个答案:

答案 0 :(得分:2)

尝试使用完全用于此目的的HAVING()子句(对聚合列进行过滤):

SELECT t.x,count(t.x) as cnt
FROM YourTable t
WHERE < >
GROUP BY t.x
HAVING count(t.x) > 10

答案 1 :(得分:0)

嗯,没有办法加快这个查询,只能处理WHERE表达式