[英]MySQL: Sum of multiple subqueries
我需要通过多个子查询的结果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
像这样尝试
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.