Quote:
Originally Posted by RustyBrooks
A quick SQL question - specifically mysql maybe.
I have a huge table, and I want to generate counts of things that match a query, grouped by subtype. Like, say
select type, count(*) from mytable where (query)
This is WAY slower than it should be, partly because query contains a lot of things that can not be indexed. But really what I want to know is "are there results for each type", i.e. I am not concerned with the real number. I want to know if it's, like, less than 10 or more than 10.
Is there a way to do this? If it was just one count I wanted I'd do
select count(*) from table where (query) limit 11
and this would usually be super fast
I guess what I kind of want is a limit on each count. Preferably without having to break it out into N queries (one for each type).
Oh my... why?
Without seeing the query, you may want to consider using a pattern like this (assuming you can't do what was already suggested):
Code:
select col1 ,count(col) cnt
from my_table t1
where exists
(select *
from other_table t2
where t1.col2 = t2.col2)
group by col1
having cnt >= 10; -- you want to know ten, right?
As far as I know, using where exists is universally faster, so should work with MySQL.
But my intuition tells me that you may be best off using pure joins all the way through, like so:
Code:
select col, count(col) cnt
from my_table
join (other_table)
using (col)
join (next_table)
using (col)
etc...
group by col
having cnt >= 10;