MySQL查询与基于其他操作结果的操作

时间:2015-11-04 07:00:34

标签: mysql sql

我需要根据其他操作结果进行操作。例如:

SELECT
    SUM(first_column) as res1,
    SUM(second_column) as res2,
    res1/res2 as res3 
FROM my_table

但似乎只能对现有列进行操作。这个用例的解决方法是什么?

5 个答案:

答案 0 :(得分:2)

您可以使用子查询来实现这一目标。 像这样:

SELECT res1, res2, res1/res2 as res3 
(SELECT SUM(xxx) as res1, SUM(xxx) as res2
FROM yyy) as subquery

答案 1 :(得分:1)

尝试类似:

SELECT res1/res2 as res3
FROM (SELECT SUM(xxx) as res1, SUM(xxx) as res2 
      FROM yyy))

答案 2 :(得分:1)

SELECT res1/res2 as res3
FROM (SELECT SUM(xxx) as res1, SUM(xxx) as res2 
FROM yyy))

这应该有效

答案 3 :(得分:1)

您可以使用此代码块解决您的问题:

select t.res1
  ,t.res2
  ,t.res1 / t.res2 as res3
from (select sum(xxx) as res1
          ,sum(xxx) as res2
      from yyy) t

不推荐,但有效。

select sum(xxx1) as res1
  ,sum(xxx2) as res2
  ,sum(xxx1) / sum(xxx2) as res3
  from yyy

答案 4 :(得分:0)

如果您不需要中间结果,则可以通过跳过子查询来获得更好的性能:

SELECT SUM(c1) / SUM(c2) AS res FROM t