2011-03-02 46 views
0

如何獲取此代碼以顯示每本客戶訂購圖書總金額的總價格?我試着用總和(在php中使用sql的總和字段

我有以下代碼:

<style type="text/css"> 
table{font-size:1.11em;} 
tr{background-color:#eee; border-top:1px solid #333;} 
</style> 
<?php 
$con = mysql_connect("localhost","root","pass"); 
if (!$con) 
{ 
    die('Could not connect: ' . mysql_error()); 
} 

mysql_select_db("bookorama", $con); 

$sql="SELECT customers.name, books.title, books.isbn, books.price 
     FROM customers, orders, order_items, books 
     WHERE customers.customerID = orders.customerID 
     AND orders.orderID = order_items.orderID 
     AND order_items.isbn = books.isbn;"; 

$result = mysql_query($sql);  // You actually have to execute the $sql with mysql_query(); 
if($result === FALSE) { 
    die(mysql_error()); // TODO: better error handling 
} 
echo "<h1 style='color:#3366ff;'>Each customer's book orders</h1>"; 
echo "<table>"; //start the table 

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results 
{ 
    //echo each row of the table 
    echo "<tr>";    
    echo "<th><strong>Customer Name:</strong><br></th>";    
    echo "<td>$row[name]</td>";  
    echo "<th><strong>Book Title</strong><br></th>";     
    echo "<td>$row[title]</td>"; 
    echo "<th><strong>ISBN</strong><br></th>"; 
    echo "<td>$row[isbn]</td>"; 
    echo "<th><strong>Book Price</strong><br></th>"; 
    echo "<td>$row[price]</td>"; 
    echo "</tr>"; 
} 

echo '</table>'; //close out the table 

?> 
+0

沒有最完美的解決方案,但有沒有理由不在你的while循環中分配一個變量'$ priceSum'並且執行'$ priceSum + = $ row [price];'' – Farray 2011-03-02 20:48:31

+0

請不要發佈無關代碼的牆 - 你在問如何寫一個查詢,所以我們不需要看到任何的PHP或HTML代碼。 – 2011-03-02 20:48:45

回答

2
SELECT customers.name, SUM(books.price) 
FROM customers, orders, order_items, books 
WHERE customers.customerID = orders.customerID 
AND orders.orderID = order_items.orderID 
AND order_items.isbn = books.isbn 
GROUP BY customers.customerID; 
0

什麼是您的SUM()查詢是這樣的:?

$sql="SELECT customers.name, books.title, books.isbn, SUM(books.price)   
FROM customers, orders, order_items, books   
WHERE customers.customerID = orders.customerID   
AND orders.orderID = order_items.orderID   
AND order_items.isbn = books.isbn GROUP BY customers.name"; 
+0

是的,但是這並沒有給我所需的輸出,它應該顯示每個客戶的總數,而不是所有客戶訂單的總和。 – Jshee 2011-03-02 20:53:14

+0

GROUP BY customers.name子句應完全按照您的要求進行:每位客戶的總數。馬克B打敗了我 - 看到他的答案。 books.title和books.isbn在輸出中是不相關的。 – Simon 2011-03-02 21:00:27