【问题标题】:MySQL: Sum of multiple subqueriesMySQL:多个子查询的总和
【发布时间】:2014-04-12 04:22:49
【问题描述】:

我需要通过多个子查询的总和来订购MySQL 查询。

这是我正在尝试做的一些示例代码:

SELECT  ...
        (SELECT SUM(
           (SELECT one_result ... LIMIT 1) as plays1,
           (SELECT one_result ... LIMIT 1) as plays2,
           (SELECT one_result ... LIMIT 1) as plays3
        )) as total_plays
FROM plays
ORDER BY total_plays

基本上,我需要运行三个子查询,每个子查询都会返回一个整数。

我需要通过这些整数的SUM() 对整个查询进行排序。

当我尝试运行此查询时,出现语法错误。

谁能告诉我对多个子查询求和的正确语法是什么?

我也试过了:

SELECT  ...
        (SELECT one_result ... LIMIT 1) as plays1,
        (SELECT one_result ... LIMIT 1) as plays2,
        (SELECT one_result ... LIMIT 1) as plays3
        SUM(plays1, plays3, plays3) as total_plays
FROM plays
ORDER BY total_plays

编辑

@JoeC 和 @SATSON 提供了解决此问题的类似答案。这是我的(工作)真实查询,以防其他人开始他们自己的查询:

````

SELECT  song.title as title,
        song.file_name as unique_name,
        song.artist as artist,
       (SELECT difficulty FROM chart WHERE id = song.easy_chart ORDER BY scoring_version ASC LIMIT 1) as easy_difficulty,
       (SELECT difficulty FROM chart WHERE id = song.hard_chart ORDER BY scoring_version ASC LIMIT 1) as hard_difficulty,
       (SELECT difficulty FROM chart WHERE id = song.master_chart ORDER BY scoring_version ASC LIMIT 1) as master_difficulty,
       (plays.easy_plays + plays.hard_plays + plays.master_plays) as total_plays
FROM song
INNER JOIN (SELECT parent_song_id,
               (SELECT global_plays ORDER BY scoring_version ASC LIMIT 1) as easy_plays,
               (SELECT global_plays ORDER BY scoring_version ASC LIMIT 1) as hard_plays,
               (SELECT global_plays ORDER BY scoring_version ASC LIMIT 1) as master_plays
       FROM chart) as plays
ON plays.parent_song_id = song.id
ORDER BY total_plays DESC
LIMIT 9
OFFSET 0

````

【问题讨论】:

    标签: mysql sum subquery


    【解决方案1】:

    嗯,怎么样

    SELECT *, plays1 + plays2 + plays3 as total_play from 
    (SELECT  ...
            (SELECT one_result ... LIMIT 1) as plays1,
            (SELECT one_result ... LIMIT 1) as plays2,
            (SELECT one_result ... LIMIT 1) as plays3
    FROM plays)
    ORDER BY total_plays
    

    【讨论】:

    • #1054 - “字段列表”中的未知列“plays1”
    • 那行得通。对于任何感兴趣的人,我已经编辑了我的问题以显示真实的查询,以防其他人形成他们自己的查询。
    【解决方案2】:

    这样试试

    SELECT  sum(plays1) as total_plays from (
            (SELECT one_result as plays1  ... LIMIT 1)
            union all 
            (SELECT one_result as plays1 ... LIMIT 1 )
            union all
            (SELECT one_result as plays1 ... LIMIT 1)
          )
    as  plays
    ORDER BY total_plays
    

    【讨论】:

      猜你喜欢
      • 2011-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多