Postgresql “内部连接”;“多对多”;表行作为数组
我是PostgreSQL的新手,正在尝试解决以下问题。假设我有三张桌子: 商店Postgresql “内部连接”;“多对多”;表行作为数组,postgresql,Postgresql,我是PostgreSQL的新手,正在尝试解决以下问题。假设我有三张桌子: 商店 | store_id | |----------| | 1 | | 2 | | 3 | | product_id | |------------| | 1 | | 2 | | 3 | 产品 | store_id | |----------| | 1 | | 2 | | 3 |
| store_id |
|----------|
| 1 |
| 2 |
| 3 |
| product_id |
|------------|
| 1 |
| 2 |
| 3 |
产品
| store_id |
|----------|
| 1 |
| 2 |
| 3 |
| product_id |
|------------|
| 1 |
| 2 |
| 3 |
商店有产品
| store_id | product_id |
|----------|------------|
| 1 | 3 |
| 1 | 2 |
| 2 | 1 |
| 3 | 3 |
| 1 | 1 |
| 3 | 1 |
| 3 | 2 |
现在我尝试构建一个查询,将所有产品连接到stores表,并将它们分组到一个数组中,这样我就有了如下输出:
| store_id | products |
|----------|-----------|
| 1 | {3, 2, 1} |
| 2 | {2} |
| 3 | {3, 1, 2} |
我知道PostgreSQL可以使用数组,但我不知道如何编写这样的查询,可能已经花了太多时间考虑解决方案
谢谢你的帮助 如果您使用的是
8.4版或更高版本,则可以使用array\u agg
:
SELECT store_id, array_agg(product_id::text) as products
FROM store_has_product
GROUP BY store_id
你能给我们提供到目前为止你建立的查询吗?