与 unnest 函数相反的 Postgresql 是什么,用于从结果集创建数组



我有一个部门 --

所以像select dept_name, xxxxxxx from dept,emp where emp_dept_id = dept_id

返回

department1 | fred,bill,joe
department2 | faith, hope, charity

我会推荐数组:

select d.dept_name, array_agg(e.name)
from dept d join 
emp e
on e.emp_dept_id = d.dept_id
group by d.dept_name;

如果您确实喜欢字符串,也可以使用string_agg(e.name, ',')

笔记:

  • 切勿FROM子句中使用逗号。
  • 始终使用正确、明确、标准、可读JOIN语法。
  • 限定引用多个表的查询中的所有列名。
  • 使用表别名,以便查询更易于编写和读取。

最新更新