【问题标题】:How to display combined rows in the database table with same ID如何在具有相同ID的数据库表中显示组合行
【发布时间】:2014-08-13 04:00:40
【问题描述】:

我有一个问题要问专家。我不知道如何将所有订单 ID 与相同的 ID 结合起来,

如图所示,所有订单 ID = 1 的订单都在一次交易中,我如何将所有具有相同 ID 的订单 ID 合并,并仅显示所有购买的商品的总价。并且由于所有订单 ID 都相同,因此交付和付款选项也将相同,只需显示一行。

还有一个后续问题是,如果我将所有相同的订单 ID 组合在一起,我将如何显示所有购买的产品,计算总价并在一行中显示交货和付款选项

这是我的数据库关系的图片,我只是关注互联网上的那些。唯一的区别是“products”改为“inventory”,products中的“serial”改为“prod_id”

这是我显示当前图片的代码。

<?php
    session_start();
    $conn = @mysql_connect("localhost","root","");
    $db = @mysql_select_db("");

$qry = "SELECT customers.name,customers.payment,customers.carrier, orders.date, order_detail.productid, order_detail.quantity, order_detail.price, order_detail.orderid, inventory.prod_name 
        FROM customers 
        RIGHT JOIN orders on customers.serial=orders.serial 
        RIGHT JOIN order_detail on orders.serial=order_detail.orderid 
        LEFT JOIN inventory on order_detail.productid=inventory.prod_id where customers.email='{$_SESSION['email']}'";

mysql_set_charset("UTF8");
$result = @mysql_query($qry);
if($result === FALSE) {
    die(mysql_error()); // TODO: better error handling
}
echo "<center>";
echo "<table class='CSSTableGenerator'>
<tr>

<td>Date of Purchase</td>
<td>First Name</td>
<td>Order ID</td>
<td>Products</td>
<td>Quantity</td>
<td>Total Price</td>
<td>Delivery Option</td>
<td>Payment Option</td>

<tr>";
while ($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['orderid']."</td>";
echo "<td>".$row['prod_name']."</td>";
echo "<td>".$row['quantity']."</td>";
echo "<td>".($row['price']*$row['quantity'])."</td>";
echo "<td>".$row['carrier']."</td>";
echo "<td>".$row['payment']."</td>";
echo "</tr>";
    }
echo "</table>";
?>
</table>

【问题讨论】:

  • 使用 sum(total_price) where id=1,当你得到你的订单 id 时,只要选择就会为你获取所需的详细信息,然后如果数据重复然后在最后一次显示它来解决你的问题问题,如果你愿意,你可以规范化表格以删除冗余数据
  • 也就是说,我们可以有一个单独的表来存储 orderid、firstname、dateofpurchase、delivery option、payment option,从而减少冗余。 orderid 将是表之间的公因子,以便获取数据

标签: php mysql merge


【解决方案1】:

对于这个特定问题,您似乎需要学习的是 SQL Group By 子句。

这个(未经测试,可能需要微调)应该可以解决问题。请注意,您无法从中获得订单商品的数量,但我会说有可能获得它们。

SELECT o.date, c.name, o.serial as 'Order Id', GROUP_CONCAT(p.name) as 'Products', SUM(od.price) as 'Total', c.carrier, c.payment
FROM orders o
JOIN customers c on o.customer_id = c.serial
JOIN orderdetail od on o.serial = od.orderid
JOIN products p on od.productid = products.prod_id
GROUP BY o.serial

特别值得注意的是 MySQL 中一个方便的聚合函数,称为 GROUP_CONCAT。 http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

【讨论】:

  • 它会做什么?按序列分组后?
  • Group By 跨多条记录收集数据。因此,仅通过分组,您将只剩下一行。然后使用聚合函数,例如 sum()、avg() 或 group_concat(),您可以对该组中的所有数据进行计算。所以显然 sum(qty) 与“按序列分组”相结合将得到该序列所有行的数量之和。
猜你喜欢
  • 2012-11-17
  • 2013-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 2014-10-08
相关资源
最近更新 更多