2

我想知道从 MySQL 数据库获取数据的哪种方式具有更好的性能特征。

在一个主查询中使用子查询:

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`

或者,3 个不同的SELECT语句检索相同的数据。

提前致谢!

4

1 回答 1

8

由于这三个聚合来自具有相同WHERE条件的同一张表,因此您不需要子选择。所有三个聚合都在同一个行分组上操作(没有GROUP BY指定,所以整个表的一行),因此它们都可以SELECT直接存在于列表中。

SELECT
  SUM(number) AS number_sum,
  MAX(number) AS number_max,
  MIN(number) AS number_min
FROM `table`

如果任何聚合需要基于您将在WHERE子句中过滤的不同条件,那么您将需要对不同条件使用子选择,或者进行笛卡尔连接。LEFT JOIN对于仅返回一行的聚合,此子选择和以下方法在性能方面应该是等效的:

SELECT
  /* Unique filtering condition - must be done in a subselect */
  (SELECT SUM(number) FROM `table` WHERE `somecolumn` = `somevalue`) AS number_sum,
  MAX(number) AS number_max,
  MIN(number) AS number_min
FROM `table`

或者等效于上面的查询,您可以LEFT JOIN针对没有ON子句的子查询。这只应在您知道子查询将仅返回一行的情况下进行。否则,您将得到一个笛卡尔积——连接一侧返回的行数乘以另一侧返回的行数。

如果您需要返回具有一组WHERE子句条件的几列和具有一组不同条件的几列WHERE但仅从. 在这种情况下,它应该比使用相同子句执行两个子选择更快。JOINJOINWHERE

这应该更快....

SELECT
  /* this one has two aggregates sharing a WHERE condition */
  subq.number_sum_filtered,
  subq.number_max_filtered,
  /* ...and two aggregates on the main table with no WHERE clause filtering */
  MAX(`table`.number) AS number_max,
  MIN(`table`.number) AS number_min
FROM
  `table`
  LEFT JOIN (
    SELECT 
       SUM(number) AS number_sum_filtered,
       MAX(number) AS number_max_filtered
    FROM `table`
    WHERE `somecolumn = `somevalue`
  ) subq /* No ON clause here since there's no common column to join on... */

比这个...

SELECT
  /* Two different subselects each over the same filtered set */
  (SELECT SUM(number) FROM `table` WHERE `somecolumn` = `somevalue`) AS number_sum_filtered,
  (SELECT MAX(number) FROM `table` WHERE `somecolumn` = `somevalue`) AS number_max_filtered,
  MAX(`table`.number) AS number_max,
  MIN(`table`.number) AS number_min
FROM
  `table`
于 2012-09-03T01:31:15.710 回答