[英]How do I write an sql query to display items from 2 tables based on a selection of a criteria which is from a different table
How do I write an sql query to display items from 2 tables based on a selection of a criteria which is from a different table. 如何编写一个sql查询以根据来自不同表的条件的选择显示2个表中的项目。
Tables I have: 我有的表:
So when a CustomerID is selected, I want the orders to be displayed joining these 3 tables. 因此,当选择了CustomerID时,我希望将这3个表一起显示订单。 so as below it should display all the orders that the customer has ever placed.
因此,如下所示,它应该显示客户曾经下过的所有订单。 I tried using the query:
我尝试使用查询:
Select CustomerOrder.*, OrderItem.*
From CustomerOrder
INNER JOIN OrderItem Where Customer.CustomerID = $CustomerID
But it's not working. 但这不起作用。 Need help in the query and also in displaying the data properly using php.
在查询以及使用php正确显示数据时需要帮助。
Can anyone help? 有人可以帮忙吗?
Eg 例如
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:_________
像这样尝试: 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
Since you don't need to display Customer information at this step, then you query can be : 由于您无需在此步骤中显示客户信息,因此您可以查询:
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
As you'd like to no repeat order information in your output, your PHP code should be soemthing like this: 由于您不希望在输出中重复订单信息,因此您的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>";
}
Anothere way of doing the same is to first get all the Orders information from CustomerOrder
only. 另一种方法是首先仅从
CustomerOrder
获取所有Orders信息。 And then loop on the result and get items infotmation OrderItem
for each order. 然后循环的结果,并得到infotmation项目
OrderItem
每个订单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.