I’m wondering which way to get data from a MySQL database has better performance characteristics.
Using subqueries within one main query:
SELECT
(SELECT SUM(`number`) FROM `table`) as `number_sum`,
(SELECT MAX(`number`) FROM `table`) as `number_max`,
(SELECT MIN(`number`) FROM `table`) as `number_min`
Or, 3 distinct SELECT statements retrieving the same data.
Thanks in advance!
Since these three aggregates come from the same table with the same
WHEREconditions, you have no need for subselects. All three of the aggregates are operating on the same row grouping (noGROUP BYspecified, so one row for the whole table), so they can all exist in theSELECTlist directly.If any of the aggregates needs to be based on different conditions you would filter in a
WHEREclause, then you will need to either use a subselect for the differing condition, or do a cartesian join. This subselect and the followingLEFT JOINmethod should be equivalent, performance-wise for aggregates returning only one row:Or equivalent to the query above, you can
LEFT JOINagainst a subquery with noONclause. This should only be done in situations when you know the subquery will return only one row. Otherwise, you will end up with a cartesian product — as many rows as returned by one side of the join multiplied by the number of rows returned by the other side.This is handy if you need to return a few columns with one set of
WHEREclause conditions and a few columns with a different set ofWHEREconditions, but only one row from each side of theJOIN. In this case, it should be faster toJOINthan to do two subselects with the sameWHEREclause.This should be faster….
Than this…