【问题标题】:使用 postgresql 根据包含来自 table1 的 count() 的选择查询更新 table2 中的列
【发布时间】:2021-12-25 21:30:33
【问题描述】:

Tables

需要根据员工表的 dno 列中每个部门工作的员工人数更新部门表的 dcount 列。 尝试使用 update department set dcount=(select count() from employee INNER JOIN department ON employee.dno=department.dnumber group by dno);* 这给出了一个错误:用作表达式的子查询返回了不止一行

想要的结果是:

**dname|dnumber|dcount

研究|5|4

管理员|4|3

总部|1|1**

需要帮助。 提前致谢。 格鲁希斯

【问题讨论】:

  • 我建议不要这样做;只需在每次需要时计算它们,否则只会给自己带来维护上的麻烦

标签: sql postgresql sql-update subquery aggregate-functions


【解决方案1】:

您的子查询 (select count() ...) 返回几行,每个员工一行,其中 postgres 期望此子查询中只有一行,以便一次更新 department 表中的一行。在这种情况下,您可以使用 cte 代替:

WITH list AS
(
select dno, count(*) AS dno_count
  from employee
 group by dno
)
update department AS d
   set dcount = l. dno_count 
  from  list AS l 
 where d.dnumber = l.dno ;

【讨论】:

  • 这行得通。非常感谢 Edouard H 先生。
猜你喜欢
  • 2020-10-22
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
相关资源
最近更新 更多