0

如何编写一个 sql 查询以根据选择的来自不同表的条件来显示 2 个表中的项目。

我有的表:

  1. 客户表有列 CustomerID、Name、Address、Tel
  2. CustomerOrder表包含 CustomerID、OrderID、Date、TotalAmount、Status 列
  3. OrderItem表包含 OrderID、ProductCode、UnitPrice、Qty、TotalPrice 列

因此,选择CustomerId时,我希望订单显示加入这3个表。如下所示,它应该显示客户曾经下过的所有订单。我尝试使用查询:

Select CustomerOrder.*, OrderItem.*
From CustomerOrder
INNER JOIN OrderItem Where Customer.CustomerID = $CustomerID

但它不起作用。在查询以及使用 php 正确显示数据时需要帮助。

任何人都可以帮忙吗?

例如

CustomerID:__________

OrderID:__1____ Date:______ TotalAmount:______ Status:_____
ProductCode:__ UnitPrice:___ Qty:_____TotalPrice:__________
ProductCode:___ UnitPrice:______ Qty:_____ TotalPrice:_________

OrderID:___2___ Date:______ TotalAmount:______ Status:_____
ProductCode:__ UnitPrice:___ Qty:_____TotalPrice:__________
ProductCode:___ UnitPrice:______ Qty:_____ TotalPrice:_________
4

2 回答 2

0

试试这样: SELECT co.OrderID,date,TotalAmount,ProductCode, UnitPrice,Qty,TotalPrice,Status FROM CustomerOrder AS co INNER JOIN OrderItem AS oi ON oi.orderID = co.OrderID INNER JOIN Customer AS c ON c.CustomerID = co.CustomerID WHERE c.CustomerID = $customer

于 2012-07-26T07:54:39.697 回答
0

由于您不需要在此步骤显示客户信息,因此您可以查询:

SELECT co.OrderID
,co.Date
,co.TotalAmount
,co.Status
,ci.ProductCode
,ci.UnitPrice
,ci.Qty
,ci.TotalPrice
FROM CustomerOrder AS co
INNER JOIN OrderItem AS ci ON (ci.orderID = co.OrderID)
WHERE co.CustomerID = $customer
ORDER BY co.OrderID, ci.ProductCode

由于您不想在输出中重复订单信息,因此您的 PHP 代码应该是这样的:

$current_order_id = false;
foreach ($data as $row) {
   if ($current_order_id!==$row['OrderID']) {
        $current_order_id = $row['OrderID'];
        echo "OrderID: ".$row['OrderID']." , Date: ".$row['Date']." , TotalAmount: ".$row['TotalAmount']." , Status: ".$row['Status']." <br>";
   }
   echo "ProductCode: ".$row['ProductCode']." , UnitPrice: ".$row['UnitPrice']." , Qty: ".$row['Qty']." , TotalPrice: ".$row['TotalPrice']." <br>";
}

CustomerOrder另一种方法是首先从only获取所有 Orders 信息。然后循环结果并获取OrderItem每个订单的项目信息。

于 2012-07-26T08:15:11.490 回答