2012-04-20 86 views
0

好吧我有3個表格,其中包含產品,其中一個帶有訂單,並與訂單ID和產品ID聯接表以將產品與訂單相關聯。Mysql如何選擇所有訂單和訂單中的項目

但是,如何設置一個查詢來選擇並返回所有訂單以及每個訂單中的項目。所以我最後在每一行都有一個列order_items。

到目前爲止,我有:

SELECT 
    intOrderID AS Order_ID, 
    strPaymentMethod AS Payment_Method, 
    strPaymentRef, AS Payment_Ref, 
    strPaymentStatus AS Payment_Status, 
    dtmDate AS Date, 
    curPaymentAmount AS Net_Price, 
    curShippingFee AS Shipping_Fee 
FROM tbl_mod_ShopOrders 

其他表是tbl_mod_ShopOrderItems,我需要選擇

intProductID 
strProductTitle 
curPrice 
intQty 

爲訂單中的每個項目。

我知道我需要做某種子查詢,但請注意如何構造它。

回答

0

假設你的表是PRODUCTORDER和連接表PRODUCTORDER具有鍵product_idorder_id,您可以:

SELECT o.id, GROUP_CONCAT(po.product_id) AS products_list 
FROM PRODUCT p, PRODUCTORDER po 
WHERE o.id = po.order_id 
GROUP BY o.id 
ORDER BY o.id 

作爲聚合函數使用GROUP_CONCAT。以上結果,例如:

id | products_list 
---|-------------- 
01 | 1,4,9 
02 | 2,4,6 
03 | 5 
04 | 3,5 

其中id是ORDER ID。

+0

我實際上並不需要的時候從產品表中選擇任何東西,因爲連接表具有產品標題和產品ID。但看起來沿着正確的路線 – user794846 2012-04-20 09:33:10

0

每個訂單都有幾個項目。這意味着當您選擇訂單時,每行可以有一個或多個項目。

如果您需要簡單地顯示每個訂單中的項目數量等簡單內容,則可以使用一個查詢輕鬆檢索所有信息。但是,如果您需要顯示每個訂單中商品的詳細信息(例如商品,數量,價格),那麼執行第二個查詢,檢索商品信息會更容易。 第二個查詢可以針對每個訂單執行,或者對於所有顯示的訂單僅執行一次(使用IN子句創建一個包含顯示的訂單id並且選擇屬於這些id的所有項目的數組)。

舉例詳細情況:

//$orders = array of orders retrieved by your query 

// loop through the orders to collect all ids 
$order_ids = array(); 
foreach($orders as $order) { 
    $order_ids[] = $order->Order_ID; 
} 

// build the select to retrieve all items 
$items = array(); 

// make the select only if there are orders available 
if(count($order_ids) > 0) { 
     $q = "SELECT * from tbl_mod_ShopOrderItems WHERE order_id IN (" . implode(',', $order_ids) . ") "; 
     // ... 
     // assign result to $items 
} 

後來,顯示訂單,您可以依次通過$items並檢查order_id符合當前order

foreach($orders as $order) { 
    // ... 
    // display order info 

    // display order items 
    foreach($items as $item) { 
     // if the item belongs to the current order 
     if($item->order_id == $order->order_id) { 
      // ... 
      // display the current item 
     } 
    } 
} 
+0

有一個例子嗎? – user794846 2012-04-20 09:43:35

+0

上述哪種情況適合您的問題?我不知道你是否需要這個例子。 – 2012-04-20 09:45:31

+0

關於每個訂單案例中的項目的詳細信息 – user794846 2012-04-20 09:52:46