请查看以下代码以获取更多信息。
// Finding a list of schools.
$schoolQuery = "SELECT DISTINCT stud_school AS schools FROM students";
$schoolsList = mysqli_query($conn, $schoolQuery);
while ($row = mysqli_fetch_assoc($schoolsList)) {
echo $row['schools'];
}
echo "<br>";
上面的代码应该在我的数据库表中的列中收集唯一值。
这是输出:
ArkCCAPM(Ark,CCA和PM是学校的首字母)。
$allSchools = mysqli_real_escape_string($row['schools']);
// Sums upp all the points recieved by each student for specific school
$myQuery = "SELECT SUM(result_studpoints) AS total FROM result WHERE stud_id IN (SELECT stud_id FROM students WHERE stud_school = 'CCA')";
$result = mysqli_query($conn, $myQuery);
$data = mysqli_fetch_assoc($result);
echo "Total CCA: ".$data['total'];
以上代码仅计算学校CCA的总积分。 我想要做的是使用唯一值(列出我数据库中的所有学校)并将其实现到上面的计算代码中,这样它不仅可以计算CCA的总数,还可以计算出唯一值中列出的所有学校的总数。 所以输出看起来像这样:
Total CCA: 16
Total PM: 17
Total Ark: 9
提前致谢。
答案 0 :(得分:0)
$allSchools = mysqli_real_escape_string($row['schools']);
// Sums upp all the points recieved by each student for specific school
$myQuery = "SELECT students.stud_school, SUM(result_studpoints) AS total FROM result JOIN students ON students.stud_id = result.stud_id GROUP BY students.stud_school";
$result = mysqli_query($conn, $myQuery);
$data = mysqli_fetch_assoc($result);
echo "Total " . $data['stud_school'] . ": ".$data['total'] . "<br />";
答案 1 :(得分:0)
试试这个:
// Finding a list of schools.
$schoolQuery = "SELECT DISTINCT stud_school AS schools FROM students";
$schoolsList = mysqli_query($conn, $schoolQuery);
while ($row = mysqli_fetch_assoc($schoolsList))
{
$allSchools = mysqli_real_escape_string($conn, $row['schools']);
// Sums upp all the points recieved by each student for specific school
$myQuery = "SELECT SUM(result_studpoints) AS total FROM result WHERE stud_id IN (SELECT stud_id FROM students WHERE stud_school = '$allSchools')";
$result = mysqli_query($conn, $myQuery);
$data = mysqli_fetch_assoc($result);
echo "Schools: ".$row['schools']." --> Total CCA: ".$data['total'];
echo "<br>";
}
答案 2 :(得分:0)
您可以直接使用此唯一查询,而不是首先查询学校列表,然后使用返回的结果通过其他查询获得最终结果:
$myQuery = "
SELECT SUM(result_studpoints) AS total, school
FROM result
JOIN students ON result.stud_id = students.stud_id
GROUP BY school
";
然后按照您的计划使用其结果。
注意:正如一些评论已经指出的那样,你与$allSchools = mysqli_real_escape_string($row['schools']);
之类的东西无关:mysqli_real_escape()
在写入数据库之前仅用于,而不是在阅读之后从它!