我需要通过多个子查询的结果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
````
答案 0 :(得分:1)
尝试这样
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
答案 1 :(得分: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