php - 在php中使用sql求和字段

标签 php mysql

如何获取此代码来显示每个客户的图书订单总金额的总价?我尝试使用 sum(

我有以下代码:

<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

?>

最佳答案

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;

关于php - 在php中使用sql求和字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5173217/

相关文章:

mysql - 1044 - 拒绝用户 'user' @'localhost' 访问数据库 'db'

php - 如何预测系统资源需求?

mysql - MySQL 中不可打印的字符

php - 选择搜索日期之前删除的所有行和软删除行

php - MySQL SELECT SUM 基于另一个表(另一个案例)

PHP - 获取站点的图标并在必要时将其转换为 png

php - 用 php 启动一个守护进程

sql - postgres 列别名问题

javascript - 用 js 在 twig 中进行循环

php - 开发与生产数据库