简体   繁体   中英

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.

Tables I have:

  1. Customer table has columns CustomerID, Name, Address, Tel
  2. CustomerOrder table has columns CustomerID, OrderID, Date, TotalAmount, Status
  3. OrderItem table has columns OrderID, ProductCode, UnitPrice, Qty, TotalPrice

So when a CustomerID is selected, I want the orders to be displayed joining these 3 tables. 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.

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:

$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. And then loop on the result and get items infotmation OrderItem for each order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM