PostgreSQL将表与一对多关系组合在一起

时间:2014-01-30 16:53:51

标签: sql postgresql psql

我正在尝试确定执行以下操作的最佳方法(即使我知道如何使用PHP等服务器端代码轻松完成此操作,我希望尽可能只使用postgreSQL。)

我有一张表格,列出了公司当前所有客户订购商品的数量以及交货日期。例如:

Top Level Item, Quantity, Delivery Date
top_item_1, 5, 20140205
top_item_2, 10, 20140215
etc...

我有另一张表,其中包含顶级项目列表(客户将订购的项目)以及我们需要购买的相应组件以制作该项目以及所购买组件的数量。例如:

Top Level Item, Component, Quantity
top_item_1, component_1, 1
top_item_1, component_2, 4
top_item_1, component_3, 2
top_item_2, component_1, 2
top_item_2, component_4, 1
etc...

现在我的问题是如何组合这些表格,以便我可以获得当前客户订单的所有必需购买项目的清单,到期时间以及到期日需要多少。例如:

Component, Quantity, Delivery Date
component_1, 5, 20140205
component_2, 20, 20140205
component_3, 10, 20140205
component_1, 20, 20140215
component_4, 10, 20140215
etc...

我为这个冗长的问题道歉。非常感谢上述任何帮助!

谢谢你, 〜丹尼尔

2 个答案:

答案 0 :(得分:0)

您描述的问题需要join两个表:

SELECT c.component, c.quantity * qli.quantity AS qunatity, delivery_date
FROM   coponnets c
JOIN   top_level_items tli ON c.top_level_item = tli.top_level_item

答案 1 :(得分:0)

http://sqlfiddle.com/#!2/bca70/4

select p.component
     , o.delivery_date
     , sum(o.quantity * p.ratio) as quantity
from orders o
     inner join pack_items p on o.item = p.item
group by p.component, o.delivery_date
order by o.delivery_date, p.component
相关问题