SELECT AVG(`col5`)
FROM `table1`
WHERE `id` NOT IN (
SELECT `id` FROM `table2`
WHERE `col4` = 5
)
group by `col2` having sum(`col3`) > 0
UNION
SELECT MAX(`col5`)
FROM `table1`
WHERE `id` NOT IN (
SELECT `id` FROM `table2`
WHERE `col4` = 5
)
group by `col2` having sum(`col3`) = 0
For readability and performance reasons, I think this code could be refactored. But how?
EDITIONS
-
removed the outer select
-
made the first select to return a sum and the second one to return another value
-
replaced the
SUMbyAVG
The outer select is missing the
FROMclause and was not adding anything so I removed it. TheNOT INis inefficient compared to the LEFT OUTER JOIN method so I replaced that. The twoUNIONs were easily combined into one by using>=.Update:
Note the use of
UNION ALLrather thanUNION. I don’t think you want to remove duplicates, and it will perform faster this way.