Optimize H2 query: SELECT COUNT(*) FROM table WHERE x=y

那年仲夏 提交于 2019-12-14 04:06:24

问题


I have a query that looks like this:

EXPLAIN ANALYZE 
select count(*) from Table t 
where t.outcome='SUCCESS'

The 'outcome' column has an index.

H2 tells me thats its using the index, but I still get something close to a full table scan, because most rows have 'SUCCESS' set, and cardinality is very low.

Is there a way to speed this up? Btw., queries without the 'WHERE' part are very fast, just as the doc says.


回答1:


What should work is using 3 subqueries:

select
  (select count(*) from table) - 
  (select count(*) from table where outcome<'SUCCESS') -
  (select count(*) from table where outcome>'SUCCESS')
as count

This should be fast because the first part is a direct lookup, and the two other queries should be fast (because most outcome is usually 'SUCCESS').

If not, could you get the query plan and add it to the question (explain analyze select ...)?



来源:https://stackoverflow.com/questions/15883629/optimize-h2-query-select-count-from-table-where-x-y

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!