2016-05-18 81 views
1

我想通過一個查詢,通過line_items表彙總產品skus列表。我抽象我的用例的一個簡單的例子:SQL彙總查詢與Postgres的一對多關係

我預期的結果是這樣的:

id name  skus 
1 mike bar sku1,sku2,sku3 
2 bort baz sku4 

給出模式和數據,如:

產品

id sku 
1 sku1 
2 sku2 
3 sku3 
4 sku4 

line_items

id order_id product_id 
1 1   1 
2 1   2 
3 1   3 
4 2   4 

地址

id name 
1 'bill foo' 
2 'mike bar' 
3 'bort baz' 

訂單

id address_id total 
1 2   66 
2 3   99 

這裏有一個工作的查詢,但它是不正確的,我得到的所有產品每一個訂單。我WHERE應使用orders.id

http://sqlfiddle.com/#!15/70cd7/3/0

不過,我似乎無法使用orders.id?我猜我需要使用JOINLEFT JOIN或以某種方式改變我的查詢事物的秩序......

http://sqlfiddle.com/#!15/70cd7/4

回答

1

您可以使用相關子查詢與JOIN得到的sku是清單對於每個order

SELECT 
    o.id, 
    a.name, 
    (SELECT array_to_string(array_agg(sku), ',') AS Skus 
    FROM products p 
    INNER JOIN line_items li 
     ON li.product_id = p.id 
    WHERE li.order_id = o.id 
    ) AS Skus 
FROM orders o 
INNER JOIN addresses a 
    ON a.id = o.address_id 

ONLINE DEMO

+1

'array_to_string(ARRAY_AGG(..),..)'可以用'string_agg()' –

1

一種解決方案可以是

SELECT orders.id, 
    addresses.name, 
    (SELECT string_agg(sku,',') AS skus 
    FROM products 
    WHERE id IN 
     (SELECT DISTINCT line_items.product_id 
     FROM line_items 
     WHERE line_items.order_id = orders.id)) 
FROM orders 
inner join addresses 
on orders.address_id = addresses.id 
; 

SQLFiddle

+0

@a_horse_with_no_name謝被替換你,編輯。 –

1

http://sqlfiddle.com/#!15/70cd7/12

SELECT orders.id, 
     addresses.name, 
     array_agg(DISTINCT products.sku) 
FROM orders 
LEFT JOIN addresses 
ON orders.address_id = addresses.id 
LEFT JOIN line_items 
ON line_items.order_id = orders.id 
LEFT JOIN products 
ON products.id = line_items.product_id 
GROUP BY orders.id,addresses.name