![](/img/trans.png)
[英]PHP/MySQL - Select all the rows where column from table 1 is equal to column from table 2
[英]How to select all from MySQL table where column between dates and order by column
我正在做一個項目,為學習中心建立評估領導小組。 我有一張桌子,看起來像這樣
我正在嘗試編寫一個查詢,該查詢將按CLASS在DATE范圍內從表中選擇所有查詢,為每個STUDENT_ID添加得分,然后按添加得分的降序排列以創建排行榜。 我已經閱讀了一些有關子查詢的內容,但對示例或它們的工作方式還不太了解,我還認為我需要在查詢中使用SELECT DISTINCT student_id,但是我的知識也很有限,因為我只使用過一次。
無論如何,這是我到目前為止所擁有的。
$classcheck = mysql_query("SELECT *
FROM assessment
WHERE class = '$class_info'
order by score DESC")
or die(mysql_error());
if(mysql_num_rows($classcheck) > 0){
while($row = mysql_fetch_array($classcheck)){
if(strtotime($row["date"]) > strtotime($fromdate) && strtotime($row["date"]) < strtotime($todate)){
echo $row['score'].'<p>';
}
}
}
但是我需要它來添加SCORE並通過查詢中添加的SCORE進行排序,而這是我用編寫的代碼無法實現的。
我知道應該開始使用PDO而不是mysql_query,這又使知識有限,並且我的時間已經用完了。 所有反饋將不勝感激。 哦,分數確實是一個百分比。
您不需要子查詢,只需要SUM
和GROUP BY
即可按學生計算總分,並需要WHERE
子句來限制日期。
SELECT student_name, SUM(score) AS total_score
FROM assessment
WHERE date BETWEEN '$fromdate' AND '$todate'
AND class = '$class_info'
GROUP BY student_id
ORDER BY total_score DESC
我認為GROUP BY
可以解決問題,因為您正嘗試將單個STUDENT_ID的所有分數相加。
如果我錯了,請隨時糾正我,但是下面的SQL應該可以為您提供所需的信息。
SELECT SUM(score) AS ttl_score, student_name
FROM assessment
WHERE class='$class_info'
AND date>='$start' AND date<='$end'
GROUP BY student_id ORDER BY ttl_score DESC;
$classcheck = mysql_query("Select Student_id, sum(Score) as SummedScore from assessment where class='$class_info' and
date between '$fromdate' and '$todate' Group by Student_ID Order By SummedScore"
or die(mysql_error());
if(mysql_num_rows($classcheck) > 0){
while($row = mysql_fetch_array($classcheck)){
echo $row['SummedScore'].'<p>';}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.