我试图提供从2017年参加培训课程的人那里收集的数据,并对课程提供反馈。
我想提供2017年所有课程的列表,并列出每门课程的平均评分。
我正在使用的两个表是
courses
course_id course_name
---------------------------
1 | Public speaking
2 | Social media skills
feedback
course_id overall_rating
--------------------------
1 | 3
1 | 5
1 | 4
1 | 4
2 | 3
2 | 3
2 | 4
我可以用
获取课程列表$yearscourses = "SELECT courseid,coursetitle FROM courses WHERE coursedate1 BETWEEN '2017-01-01' AND '2017-12-31'";
$yearsresult = mysqli_query($connect, $yearscourses);
平均评分
$avgrating = "SELECT AVG(overall_rating) FROM feedback WHERE courseid='courseid'";
但是我很难在使用HTML / PHP的表格中表达这一点。 我尝试了以下但是它在每一行中重复相同的平均值。
<table cellspacing="0" table border="1" cellpadding="padding:5px;">
<tr style="font-size:20px; font-weight:bold; text-align:center;">
<td colspan="4">
2017
</td>
</tr><tr style="font-weight:bold;">
<td style="background-color:#AED6F1;">Course ID</td><td style="background-color:#AED6F1;">Course title</td><td style="background-color:#AED6F1;">Average rating</td>
</tr>
<?php
// Get a list of all courses for the year
$yearscourses = "SELECT courseid,coursetitle FROM courses WHERE coursedate1 BETWEEN '2017-01-01' AND '2017-12-31'";
$yearsresult = mysqli_query($connect, $yearscourses);
if (mysqli_num_rows($yearsresult) != 0) // Search has found results
{
$str = "\n";
}
while ($row = mysqli_fetch_array($yearsresult, MYSQLI_ASSOC)) {
// Get average rating for each course
$avgrating = "SELECT AVG(overall_rating) FROM feedback WHERE courseid='courseid'";
$avgresult = mysqli_query($connect, $avgrating);
foreach($avgresult as $row2) {
echo "<tr><td>" . $row['courseid']. "</td><td>" .$row['coursetitle']. "</td><td>".$row2['AVG(overall_rating)']."</td></tr>\n";
$str .= " ";
}
}
$str .= "</table>\n</div>";
echo $str;
?>
答案 0 :(得分:1)
使用别名作为平均值
$avgrating = "SELECT AVG(overall_rating) as average_rating FROM feedback WHERE courseid='courseid'"; // use alias for avereage
和循环
echo "<tr><td>" . $row['courseid']. "</td><td>" .$row['coursetitle']. "</td><td>".$row2['average_rating']."</td></tr>\n";
答案 1 :(得分:1)
正如另一篇文章所指出的,您可以使用别名轻松访问循环中的值。话虽这么说,你应该避免在循环中执行查询。您可以利用cx_oracle Documentation子句检索相同的信息。
以下是加入feedback
表时的情况:
SELECT c.courseid, c.coursetitle, AVG(f.overall_rating) AS average_rating
FROM courses c
LEFT JOIN feedback f ON f.courseid = c.courseid
WHERE c.coursedate1 BETWEEN '2017-01-01' AND '2017-12-31'
GROUP BY f.courseid
请注意,对于此查询,未收到任何反馈的课程的NULL
值为average_rating
。
答案 2 :(得分:0)
你只需要这样做
$avgrating = "SELECT AVG(overall_rating) FROM feedback WHERE courseid='".$row['courseid']."'";
而不是那个
$avgrating = "SELECT AVG(overall_rating) FROM feedback WHERE courseid='courseid'";