Postgresql 在子查询中使用多行作为表达式
Postgresql use more than one row as expression in sub query
正如标题所说,我需要创建一个查询,其中我 SELECT
来自一个 table 的所有项目,并将这些项目用作另一个查询中的表达式。假设我的主要 table 看起来像这样:
main_table
-------------------------------------
id | name | location | //more columns
---|------|----------|---------------
1 | me | pluto | //
2 | them | mercury | //
3 | we | jupiter | //
子查询 table 如下所示:
some_table
---------------
id | item
---|-----------
1 | sub-col-1
2 | sub-col-2
3 | sub-col-3
其中 some_table
中的每件商品的价格都在 amount_table
中,如下所示:
amount_table
--------------
1 | 1000
2 | 2000
3 | 3000
这样查询 return 的结果是这样的:
name | location | sub-col-1 | sub-col-2 | sub-col-3 |
----------------------------------------------------|
me | pluto | 1000 | | |
them | mercury | | 2000 | |
we | jupiter | | | 3000 |
我的查询目前看起来像这样
SELECT name, location, (SELECT item FROM some_table)
FROM main_table
INNER JOIN amount_table WHERE //match the id's
但我 运行 陷入错误 more than one row returned by a subquery used as an expression
如何制定此查询以获得 return 所需的结果?
你应该决定预期的结果。
获得一对多关系:
SELECT name, location, some_table.item
FROM main_table
JOIN some_table on true -- or id if they match
INNER JOIN amount_table --WHERE match the id's
与所有行一对一:
SELECT name, location, (SELECT array_agg(item) FROM some_table)
FROM main_table
INNER JOIN amount_table --WHERE //match the id's
正如标题所说,我需要创建一个查询,其中我 SELECT
来自一个 table 的所有项目,并将这些项目用作另一个查询中的表达式。假设我的主要 table 看起来像这样:
main_table
-------------------------------------
id | name | location | //more columns
---|------|----------|---------------
1 | me | pluto | //
2 | them | mercury | //
3 | we | jupiter | //
子查询 table 如下所示:
some_table
---------------
id | item
---|-----------
1 | sub-col-1
2 | sub-col-2
3 | sub-col-3
其中 some_table
中的每件商品的价格都在 amount_table
中,如下所示:
amount_table
--------------
1 | 1000
2 | 2000
3 | 3000
这样查询 return 的结果是这样的:
name | location | sub-col-1 | sub-col-2 | sub-col-3 |
----------------------------------------------------|
me | pluto | 1000 | | |
them | mercury | | 2000 | |
we | jupiter | | | 3000 |
我的查询目前看起来像这样
SELECT name, location, (SELECT item FROM some_table)
FROM main_table
INNER JOIN amount_table WHERE //match the id's
但我 运行 陷入错误 more than one row returned by a subquery used as an expression
如何制定此查询以获得 return 所需的结果?
你应该决定预期的结果。
获得一对多关系:
SELECT name, location, some_table.item
FROM main_table
JOIN some_table on true -- or id if they match
INNER JOIN amount_table --WHERE match the id's
与所有行一对一:
SELECT name, location, (SELECT array_agg(item) FROM some_table)
FROM main_table
INNER JOIN amount_table --WHERE //match the id's