2012-01-07 124 views
1

說我有一個包含以下內容的數據庫:如何正確查詢數據庫中包含列表結果

orders(id, total, address_id) 
line_items(id, product_id, order_id, quantity, price) 
products(id, name, price) 
addresses(id, address) 

我需要提供以下包含報表:

Order #123 
Line Items 
    3 x Product 1 @ $3 = $9 
    2 x Product 2 @ 1 = $2 
Total: $11 
Shipping: 123 Main Street 

Order #124 
Line Items 
    1 x Product 1 @ $3 = $3 
    1 x Product 2 @ 1 = $1 
Total: $4 
Shipping: 456 Jones Ave 

所以,需要顯示訂單列表,每個訂單,ID,訂單項列表,訂單總額和送貨地址。

什麼是最好的方式做到這一點,而無需查詢每個訂單來獲取訂單項和貨運信息?

我應該有一個包含以下內容的觀點:在應用程序代碼

order_id, line_item_quantity, line_item_price, product_name, line_item_total, shipping_address 

然後按順序編號?這是我能想到的最好的,但似乎馬虎(當然,在現實世界中,每張桌子上會有更多的信息和更多的表格)。

回答

1

你需要扁平化的關係,並通過訂單ID對其進行排序:

select O.id, L.quantity, P.name, P.price, A.address, 
L.quantity * P.price subtotal, 
(
    select sum(L1.quantity * P1.price) 
    from line_items L1 
    inner join products P1 on L1.product_id = P1.id 
    where L1.order_id = O.id 
) ordertotal 
from orders O 
inner join line_items L on O.id = L.order_id 
inner join products P on L.product_id = P.id 
inner join addresses A on O.address_id = A.id 
order by O.id, L.id 

然後取決於你如何建立你的報告,嘗試通過結果行循環時檢測順序編號的變化。訂單ID更改時,是時候設置一套新的訂單。

例如,如果您使用水晶報表,您只需在訂單ID上設置新的分組,並自動分段訂單。

+0

正確,所以基本上就是我所說的 - 有一個視圖,它列出了一個平面表中的所有值,然後使用知道如何對其進行分組的應用程序代碼。 – 2012-01-07 18:06:19

相關問題