是否可以编写循环的MySQL查询?

时间:2017-06-09 09:34:12

标签: mysql

我有两个表,我想在same_team上为所有用户求值(personal_score)并暂时将其分配给team_name,然后从最高到最低排序,最后只获得最高10 ...

User
    - int id
    - varchar team_name
    - int personal_score

Team
   - int id
   - varchar team_name

所以,如果这是有道理的......结果将是......

   team_name   summed_score
   Chicago     92
   RedBulls    90
   Knights     82

其中summed_score是User表中所有personal_score值的SUM,其team_name等于Team表中的每个team_name。

现在我这样做使用PHP,但我想纯粹在SQL级别上这样做...注意我使用medoo.php在php中查询数据库。

function ComparePersonalScores($a, $b)
{
    return $b["total_score"] - $a["total_score"];
}

// Get all the Team Names possible...
$Teams = $Database->select("teams", "team_name");
$TeamResult_Objects = [];
foreach($Teams as $team)
{
    $total_score = $Database->query("SELECT SUM(personal_score) as 'summed_score' FROM users WHERE team_name='" . $team . "';")->fetchAll();

    $result_object["total_score"] = $total_score[0]["summed_score"];
    $result_object["name"] = $team;
    array_push($TeamResult_Objects, $result_object);
}

usort($TeamResult_Objects, "ComparePersonalScores");
$TeamResult_Objects = array_slice($TeamResult_Objects, 0, 10);

1 个答案:

答案 0 :(得分:1)

你不需要循环。只需使用sql builtins: 例如:

SELECT team_name, SUM(personal_score) AS summed_score FROM User GROUP BY team_name ORDER BY summed_score DESC LIMIT 10;
  • SUM总结个人得分
  • GROUP BY按团队分组
  • ORDER BY排序
  • 限制结果限制