2010-03-12 44 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