获取具有不同条件的相同列的总和

时间:2015-02-25 03:49:16

标签: mysql performance optimization

我试图减少查询的重量,并尝试通过优化查询来最小化查询量,因此我想将两个查询放在一起。

SELECT SUM(iAmount) as `shares`,
       (SELECT SUM(iAmount)
          FROM `investments`
         WHERE `iUser = 1
           AND DATE(`iTime`) = CURDATE()) as `shares_today`
  FROM `investments` WHERE `iUser` = 1

这不起作用,我做错了什么?

1 个答案:

答案 0 :(得分:2)

iUser之后你错过了一个反引号。

但无论如何,这里不需要子查询:

SELECT SUM(`iAmount`) as `shares`,
       SUM(IF(DATE(`iTime`) = CURDATE(), `iAmount`, 0)) as `shares_today`
  FROM `investments`
 WHERE `iUser` = 1;