如何在postgres中显示存储子查询结果的数组的内容和大小?

How to display the contents and size of an array storing the results of a subquery in postgres?

我想在一列中显示数组的内容,在下一列中显示数组的大小。该数组是根据我的查询中的子选择生成的。有没有一种方法可以两次引用同一个数组,这样我就不必重复子选择查询?

现在可用的查询的简化版本是:

SELECT b.id, 
       (array_to_string(array 
       ( 
                select   currency_id 
                FROM     RECORD 
                WHERE    business_id = b.id 
                GROUP BY business_id, 
                         currency_id), '|')) AS currencies, 
       array_length(ARRAY 
       ( 
                SELECT   currency_id 
                FROM     RECORD 
                WHERE    business_id = b.id 
                GROUP BY business_id, 
                         currency_id), 1) AS num_currencies 
FROM   business b

我希望从中得到如下结果:

 id  | currencies | num_currencies
-----+------------+----------------
  53 | 38|36      |              2
 235 | 36         |              1
 289 |            |
(3 rows)

查询规划器是否发现它与运行第二个查询的优化子查询完全相同,或者是否有更好的方法来获得此结果?

你不需要两次子select。如果您将 "main" 查询放入派生的 table,您可以简单地重新使用数组

SELECT id, 
       array_to_string(currencies, '|') as currencies, 
       array_length(currencies, 1) as num_currencies
FROM (
  SELECT b.id, 
         array(select   currency_id 
               FROM     record
               WHERE    business_id = b.id 
               GROUP BY business_id, 
                        currency_id) AS currencies 
  FROM   business b
) t;

优化器是否检测到相同的子查询应该从执行计划中可见。

但我认为您可以进一步简化:

select b.id, 
       string_agg(r.currency_id::text, '|') as currencies,
       count(*) as num_currencies
from business b
  join record r on r.business_id = r.id
group by b.id
order by b.id;