多个SUM的MySQL子查询

时间:2011-02-12 20:25:12

标签: mysql performance query-optimization subquery

如果我需要获得具有类似WHERE条件的五个+不同的SUM值,那么通过一个带有五个子查询的查询是最好的(也许是唯一的)方法吗?例如,我的查询是:

SELECT user, 
(SELECT SUM(amount) FROM table t, table2 t2 WHERE t.table2_id = t2.id AND table2.type = 1 AND user = 1 AND date = x) AS one,
(SELECT SUM(amount) FROM table t, table2 t2 WHERE t.table2_id = t2.id AND table2.type = 2 AND user = 1 AND date = x) AS two, 
(SELECT SUM(amount) FROM table t, table2 t2 WHERE t.table2_id = t2.id AND table2.type = 3 AND user = 1 AND date = x) AS three, 
(SELECT SUM(amount) FROM table t, table2 t2 WHERE t.table2_id = t2.id AND table2.type = 4 AND user = 1 AND date = x) AS four, 
(SELECT SUM(amount) FROM table t, table2 t2 WHERE t.table2_id = t2.id AND table2.type = 5 AND user = 1 AND date = x) AS five 
FROM table 
WHERE user = 1

到目前为止,我的查询速度非常快,但是当有更多记录时,我担心五个+子查询的含义。

出于好奇,这样一个带有五个子查询的查询是否比五个单独的查询具有性能优势/劣势?我假设它更快,因为它只有一次数据库之旅而不是5?

编辑:有大约60条记录的表2用于对表1中的数千条记录进行分类。表2中的每条记录按类型值1 - 5进行分类(这就是我正在使用的分组我希望SUM的项目。

3 个答案:

答案 0 :(得分:1)

您只需要一个查询即可获得每种类型的总和:

SELECT 
  t2.type, 
  SUM(t.amount) 
FROM 
  table t 
INNER JOIN 
  table2 t2 
ON 
  t.table2_id = t2.id 
AND 
  t.user = 1
AND 
  t.date = x 
GROUP BY 
  t2.type

答案 1 :(得分:1)

好。如果这仅适用于一个用户,而你并不是绝对需要它......你可以做这样的事情......

select user, type, sum(amount)
where user = 1
and date = x
and type between (1,5)
group by user, type

这会给你

1,1,sum
1,2,sum
1,3,sum
1,4,sum
1,5,sum

而不是

1,sum1,sum2,sum3,sum4,sum5

这应该足够好,我怀疑你没有那么麻烦。

答案 2 :(得分:1)

  1. 使用ANSI JOINS
  2. 您最好以PIVOT形式编写查询,如下面的查询
  3. <强>改写为:

    SELECT t.user, 
    SUM(CASE table2.type WHEN 1 then amount else 0 end) As one,
    SUM(CASE table2.type WHEN 2 then amount else 0 end) As two,
    SUM(CASE table2.type WHEN 3 then amount else 0 end) As three,
    SUM(CASE table2.type WHEN 4 then amount else 0 end) As four,
    SUM(CASE table2.type WHEN 5 then amount else 0 end) As five
    FROM table t
    INNER JOIN table2 t2 ON t.table2_id = t2.id 
    WHERE t.user = 1
      AND table2.type in (1,2,3,4,5)
    

    我理解您的查询是伪的,但它有一个挂起的WHERE user没有FROM子句。至于性能,上面一遍经过表格。 5x子查询形式将需要5次传递,但如果有适当的索引,则不应该明显更慢。