MySQL:多个子查询的总和

标签 mysql sum subquery

我需要根据多个子查询的结果 SUM 对 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

````

最佳答案

嗯,怎么样

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

关于MySQL:多个子查询的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23026065/

相关文章:

php - 将 CSV 中的 1 行以上插入 mysql 数据库时出现问题

php - 在 Windows 中向 PHP 添加 Mysqli 扩展时出错

python - 如何执行在Python循环中迭代的元素总和

hadoop - pig : Pivoting & Sum 3 relations

sql - SQL 中的 SUM 值从另一个表中的特定点开始

mysql - 通过组合三个不同的sql查询的数据来获取公共(public)数据

mysql - mysql 5.7 中的 ANSI 搜索

mysql - 仅用于 IS NULL 和 IS NOT NULL 的列上的索引

vba - Excel-VBA 命名范围行总和

MySQL 关联子查询 SUM() ORDER BY