2012-11-02 38 views
0

我目前在MySQL數據庫中有5個表。他們中的一些人共享外鍵並且彼此相互依賴。我正在向他們的專業顯示相應的課程。我有兩個專業:計算機工程師和信息系統。它們的值存儲在名爲major的表中。他們各自的ID是1和2.我在總計所有課程的時間方面遇到困難。我如何添加每個課程時間並在頁面底部顯示專業的總小時數?SQL查詢:添加總小時數

<? 


try { 

    $pdo = new PDO ("mysql:host=$hostname;dbname=$dbname","$username","$pw"); 
    } catch (PDOException $e) { 
    echo "Failed to get DB handle: " . $e->getMessage() . "\n"; 
    exit; 
    } 
     $query = $pdo->prepare("SELECT course.name, course.code, course.description, course.hours, 
          CASE semester.semester 
          WHEN 0 THEN 'Spring' 
          WHEN 1 THEN 'Fall' 
          WHEN 2 THEN 'All-year' 
          END semester, semester.year 
          FROM course 
          LEFT JOIN major_course_xref ON course.id = major_course_xref.course_id 
          LEFT JOIN major ON major.id = major_course_xref.major_id 
          LEFT JOIN course_semester_xref ON course.id = course_semester_xref.course_id 
          LEFT JOIN semester ON course_semester_xref.semester_id = semester.id 
          Where major.id = '1' 
          "); 
     $query->execute(); 

    if ($query->execute()){ 

     while ($row = $query->fetch(PDO::FETCH_ASSOC)){ 
     print "<b>" . $row['name'] . "</b><br>"; 
     print $row['code'] . "<br>"; 
     print $row ['description'] . "<br>"; 
     print $row['hours'] . " hrs. <br>"; 
     print $row['semester'] . "<br>"; 
     print $row['year'] . "<br>"; 
     print "------------------------------<br />"; 
    } 


    } 
else 
    echo 'Could not fetch results.'; 

     unset($pdo); 
     unset($query); 

?>  

電流輸出

Computer Programming I 
CPSC1400 
Introduction to disciplined, object-oriented program development. 
4 hrs. 
Spring 
2013 
------------------------------ 
Computer Programming II 
CPSC1500 
This course builds upon the topics covered in Computer Science I and provides experience developing complex applications. 
4 hrs. 
Fall 
2013 
------------------------------ 
Database Programming 
CPSC2100 
Study of relational database management systems and information storage and retrieval techniques. 
4 hrs. 
Spring 
2014 
+0

'SUM(course.hours)作爲TotalHours'不起作用? –

回答

1

你可以添加一個變量如$tothours那麼while子句中添加$row['hours']它。

可能會比sql語句中的另一個查詢/連接更好。

$tothours = 0; 

while ($row = $query->fetch(PDO::FETCH_ASSOC)){ 
    print "<b>" . $row['name'] . "</b><br>"; 
    print $row['code'] . "<br>"; 
    print $row ['description'] . "<br>"; 
    print $row['hours'] . " hrs. <br>"; 
    print $row['semester'] . "<br>"; 
    print $row['year'] . "<br>"; 
    print "------------------------------<br />"; 
    $tothours += $row['hours']; <-- this line 
} 

print "<p>Total hours for Major: " . $tothours . ".</p>" 

很抱歉,如果我的語法不正確。

+0

+1這聽起來很完美。你能用我的例子向我展示完整的答案嗎? – techAddict82

1

該查詢顯示您的課時由主要分組的總和:

select major.id, sum(course.hours) 
from course, major, major_course_xref 
where course.id = major_course_xref.course_id 
     and major.id = major_course_xref.major_id 
group by major.id