如何在选择查询中添加值?在我的代码下面我有5金,2银和1铜。 1金等于3点,1银是2点。我的问题是如何在选择查询中为此计算?有可能吗?
这是我的php脚本
$sql = "SELECT team.shortcut,
SUM(IF(rank = 1, 1, 0)) AS gold,
SUM(IF(rank = 2, 1, 0)) AS silver,
SUM(IF(rank = 3, 1, 0)) AS bronze
FROM team
INNER JOIN academicorg ON team.shortcut = academicorg.shortcut
GROUP BY shortcut
ORDER BY gold DESC, silver DESC, bronze DESC";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
$result = mysqli_query($con,$sql);
$response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("shortcut"=>$row[0], "gold"=>$row[1], "silver"=>$row[2], "bronze"=>$row[3], "total"=>$row[4]));
}
echo json_encode (array("news_response"=>$response));
mysqli_close($con);
?>
这是我得到的
{"news_response":[{"shortcut":"aaa","gold":"6","silver":"3","bronze":"5","total":null},
{"shortcut":"bbb","gold":"6","silver":"3","bronze":"4","total":null}
这就是我想要的。我得到的总数是29,因为金等于3分,银是2,青铜是1。
{"news_response":[{"shortcut":"aaa","gold":"6","silver":"3","bronze":"5","total"29},
{"shortcut":"bbb","gold":"6","silver":"3","bronze":"4","total":28}
答案 0 :(得分:1)
我很想尝试这个。它未经测试我没有符合要求的数据库
SELECT team.shortcut,
SUM(IF(rank = 1, 1, 0)) AS gold,
SUM(IF(rank = 2, 1, 0)) AS silver,
SUM(IF(rank = 3, 1, 0)) AS bronze,
SUM(IF(rank = 1, 3, IF(rank = 2, 2, IF(rank = 3, 1, 0)))) as total
FROM team
INNER JOIN academicorg ON team.shortcut = academicorg.shortcut
GROUP BY shortcut
ORDER BY gold DESC, silver DESC, bronze DESC