我有一个包含多个Tabletennis匹配项的数据库。 要进行排名,我需要计算多列。
我想加起来独特的回合,以了解人们参加的频率。我也想将所有获奖的游戏加起来。有时,我们玩“超级回合”(SR),获胜游戏将翻倍。 SR默认设置为1。
要知道总得分,我想将两个结果(参与和total_games)加起来。
我现在所拥有的:
$sql_user = $conn->query("
SELECT user_id, count(distinct round) as participation,
sum(IFNULL(GAMES_WIN,0) * SR) AS total_games
FROM tt_game group by user_id ORDER BY user_id ASC");
是否可以执行以下操作:
$sql_user = $conn->query("
SELECT user_id, count(distinct round) as participation,
sum(IFNULL(GAMES_WIN,0) * SR) AS total_games
sum(participation + total_games) AS total_score
FROM tt_game group by user_id ORDER BY total_score DESC");
我该如何回应这些结果? 非常感谢!
答案 0 :(得分:2)
否,您不能在SELECT
子句本身中引用SELECT
子句中定义的别名。
您可以重复以下表达式:
SELECT
user_id,
count(distinct round) as participation,
sum(IFNULL(GAMES_WIN,0) * SR) AS total_games,
count(distinct round) + sum(IFNULL(GAMES_WIN,0) * SR) AS total_score
FROM tt_game
GROUP BY user_id
ORDER BY total_score DESC;
或使用子查询:
SELECT user_id, participation, total_games, participation + total_game AS total_score
FROM
(
SELECT
user_id,
count(distinct round) as participation,
sum(IFNULL(GAMES_WIN,0) * SR) AS total_games
FROM tt_game
GROUP BY user_id
) aggregated
ORDER BY total_score DESC;
答案 1 :(得分:0)
另一个选择呢?
我认为您需要另一个选择,您可以在其中计算total_score。
尝试这样的事情:
$sql_user = $conn->query("
SELECT t.user_id, t.participation, t.total_games, (participation + total_games) AS total_score
FROM (SELECT user_id, count(distinct round) as participation, sum(IFNULL(GAMES_WIN, 0) * SR) AS total_games
FROM tt_game
group by user_id
ORDER BY total_score DESC) AS t
");