2010-03-12 40 views
0

我有兩個表,ProductsBundleProducts與BaseProducts有ooo關係。 A BundleProduct是使用與Products表格的m2m關係的Products的集合。 Products具有price列,並且BundleProduct的價格計算爲其Products的價格總和。同時查詢列和列的計算PostgreSQL

BaseProducts有像namedescription列這樣我就可以查詢它來獲取兩ProductsBundleProducts

是否可以查詢和sort by price既爲Productsprice列和計算BundleProductsprice

回答

1

嘗試這樣:

SELECT name, description, price 
FROM (
    SELECT name, description, price FROM products 
    UNION 
    SELECT bundle_products.name, bundle_products.description, sum(products.price) 
    FROM bundle_products 
    JOIN products on (<your join condition) 
    GROUP BY bundle_products.name, bundle_products.description 
) AS combined 
ORDER BY price