问题
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