mysql - Combining SQL SUM clauses -
i have script requires executing 4 rather large mysql queries on same subset of data. there way combine them 1 query?
here query looks like:
select sum(value) ( select lat, lng, value `pop_geo_199` ( (lat between 38.1768916977 , 39.6131083023) , (lng between -77.9596650363 , -76.1143349637)) ) firstcut (acos(0.627895140732*sin(radians(lat)) + 0.778297945677*cos(radians(lat))*cos(radians(lng)-(-1.34454929586))) * 6371 < 79.85)
as can tell, geographic query of latitude , longitude points. query first create simple square subset of total table (firstcut
), , runs trig functions on circular area.
from can tell, part of query slow firstcut
, because table drawing on has 2.8 million rows. firstcut
, though, in instance, has 27,922 rows, trig part goes super fast comparison.
the issue is, have run few of these. can use same firstcut
, though, since different radii centered on same area. i'd love able pull off 1 query instead of four.
here second query looks like:
select sum(value) ( select lat, lng, value `pop_geo_199` ( (lat between 38.1768916977 , 39.6131083023) , (lng between -77.9596650363 , -76.1143349637)) ) firstcut (acos(0.627895140732*sin(radians(lat)) + 0.778297945677*cos(radians(lat))*cos(radians(lng)-(-1.34454929586))) * 6371 < 48.57)
as can see same other 1 except last clause slight different — condition smaller radii (48.57 instead of 79.85).
how can combine these 2 queries 1 query in efficient way?
i've tried using case clauses -- best approach?
select sum(case when (acos(0.627895140732*sin(radians(lat)) + 0.778297945677*cos(radians(lat))*cos(radians(lng)-(-1.34454929586))) * 6371 < 79.85) value else 0 end), sum(case when (acos(0.627895140732*sin(radians(lat)) + 0.778297945677*cos(radians(lat))*cos(radians(lng)-(-1.34454929586))) * 6371 < 48.57) value else 0 end) ( select lat, lng, value `pop_geo_199` ((lat between 38.1768916977 , 39.6131083023) , (lng between -77.9596650363 , -76.1143349637)) ) firstcut;
you can use case
statement this. can move calculation subquery:
select sum(case when rad < 79.85 value else 0 end) 1stquerysum, sum(case when rad < 48.57 value else 0 end) 2ndquerysum ( select lat, lng, value, acos(0.627895140732*sin(radians(lat)) + 0.778297945677*cos(radians(lat))*cos(radians(lng)-(-1.34454929586))) * 6371 rad `pop_geo_199` ( (lat between 38.1768916977 , 39.6131083023) , (lng between -77.9596650363 , -76.1143349637) ) ) firstcut
Comments
Post a Comment