如何更新列的值?

时间:2019-04-05 04:58:29

标签: sql postgresql

我在PostgreSQL数据库中有2个名为PROJECTSPROJECTS_EMPLOYEES_RELATIONSHIP的表。如您所见,在第一个表中,我有一个名为TOTAL_EMPLOYEES的列。在该列中,我想根据第二张表的信息存储项目中的员工总数。我尝试了下一条sql语句,但引发错误。如何解决此错误?

项目

| ID (uuid)                             | TOTAL_EMPLOYEES (int) |
|---------------------------------------|-----------------------|
| 36c89a24-fff2-4cbc-a542-b1e956a352f9  | 0                     |
| 41c89a24-fff2-4cbc-a542-b1e956a352f9  | 5                     |

PROJECTS_EMPLOYEES_RELATIONSHIP

| PROJECT_ID (uuid)                     | EMPLOYEE (varchar)    |
|---------------------------------------|-----------------------|
| 36c89a24-fff2-4cbc-a542-b1e956a352f9  | NNogerbek@gmail.com   |
| 41c89a24-fff2-4cbc-a542-b1e956a352f9  | IKim@gmail.com        |

SQL

UPDATE PROJECTS
SET TOTAL_EMPLOYEES = COUNT(EMPLOYEE)
FROM PROJECTS
LEFT JOIN PROJECTS_EMPLOYEES_RELATIONSHIP
ON PROJECTS.ID = PROJECTS_EMPLOYEES_RELATIONSHIP.PROJECT_ID
WHERE PROJECTS.ID = PROJECTS_EMPLOYEES_RELATIONSHIP.PROJECT_ID;

错误

SQL Error [42712]: ERROR: table name "PROJECTS" specified more than once.

1 个答案:

答案 0 :(得分:1)

您可以在下面尝试-参见update join作为参考

UPDATE PROJECTS
SET TOTAL_EMPLOYEES = cntemployee 
FROM (SELECT PROJECT_ID, COUNT(EMPLOYEE) AS cntemployee 
      FROM PROJECTS_EMPLOYEES_RELATIONSHIP
      GROUP BY PROJECT_ID) B
WHERE PROJECTS.ID = B.PROJECT_ID