【发布时间】:2018-10-02 09:34:32
【问题描述】:
我的 PostgreSQL 9.2.8 数据库中有一个包含这三个表的表结构:
我试图弄清楚如何选择orders 行并在同一行上添加来自order_points 和points 的一些列。
您可以将points 表想象成一个人可以购买的所有物品的列表,abbrev 内部知道它,它的成本是amount。
order_points 表是购买的每件商品,因此 points.id == order_points.points_id 和 amount 类似于说他们购买了 5 个糖果棒。它通过order_points.order_id == orders.id链接到一个订单
当我选择一个订单时,我希望每个存在的abbrev 以及order_points 表中的amount 都有一个列。
所以如果points 有这个:
id | name | abbrev | amount
--------------------------------
1 | Snickers | sn | 1.34
2 | Milky Way | mw | 1.73
3 | Coffee | cf | 10.12
order_points 有这个:
id | order_id | points_id | amount
----------------------------------
1 | 1 | 1 | 10
2 | 1 | 3 | 1
然后当我得到我的行时,我想要订单中的所有列,加上三个额外的列。我不想列出上面订单中显示的每一列,但基本上假设我只想要其中的 4 个,再加上所有 points 的东西,我最终会以一行输出:
id | created | due | name | sn | mw | cf
------------------------------------------------
1 | 2018-04-21 | 2018-05-01 | Fooey | 10 | 0 | 1
我不知道如何从表查找中动态添加具有名称(abbrev)的列。
【问题讨论】:
-
您能否向我们展示所需的输出,而不仅仅是您想要的其他列
-
我在示例中添加了来自
orders的一些列 -
你可能需要postgres的
crosstab函数。这些帖子应该会有所帮助:stackoverflow.com/questions/22886327/… 和 stackoverflow.com/questions/3002499/postgresql-crosstab-query/… -
order_points.point_id 是唯一的吗?
-
points中有多少行?
标签: sql postgresql postgresql-9.2