我使用 postgresql 11。
我有一个表“portal_courses”,其中包含以下列:department_id,course_no,department_mother,status,desc_ar,desc_en 这是数据示例:
department_id, course_no,department_mother,status desc_ar desc_en
51 4516 51 1 testAR4516 testEn4516
63 8542 51 1 null null
28 8886 51 1 null null
22 8552 51 1 testAR8552 testEn8552
60 1002 39 1 testAR1002 testEn1002
70 9856 70 1 null null
71 8523 70 1 testAR8523 testEn8523
我想根据具体情况更新 desc_ar 和 desc_en。 首先检查 department_id=department_mother 并检查 desc_ar ,desc_en 是否不为空 然后更新所有其他具有相同 department_mother 的 course_no 的 desc_ar、desc_en 和 仅更新为 null 的 desc_ar、desc_en。
这是正确的结果:
department_id, course_no,department_mother,status desc_ar desc_en
51 4516 51 1 testAR4516 testEn4516
63 8542 51 1 testAR4516 testAR4516
28 8886 51 1 testAR4516 testAR4516
22 8552 51 1 testAR8552 testEn8552
60 1002 39 1 testAR1002 testEn1002
70 9856 70 1 null null
71 8523 70 1 testAR8523 testEn8523
所以只更新这一行:
63 8542 51 1 testAR4516 testAR4516
28 8886 51 1 testAR4516 testAR4516
我尝试使用此代码但没有成功:
UPDATE
portal_courses
SET
desc_ar = p1.desc_ar ,desc_en=p1.desc_en
FROM
portal_courses p1
WHERE
portal_courses.department_id = p1.department_mother
and portal_courses.status='1' and portal_courses.desc_ar is null and portal_courses.desc_en is null
and p1.desc_ar is not null and p1.desc_en is not null
尝试的查询存在两个问题,通过以下查询中的注释来标识:
UPDATE portal_courses
SET
desc_ar = p1.desc_ar,
desc_en = p1.desc_en
FROM
portal_courses p1
WHERE
-- change portal_courses.department_id to portal_courses.department_mother
portal_courses.department_mother = p1.department_mother
AND portal_courses.status = '1'
AND portal_courses.desc_ar IS NULL
AND portal_courses.desc_en IS NULL
-- add condition to identify mother rows
AND p1.department_id = p1.department_mother
AND p1.desc_ar IS NOT NULL
AND p1.desc_en IS NOT NULL
-- return changed rows to check results
RETURNING
portal_courses.*;
运行查询会产生以下输出,这表明相应的行已更新:
部门_id | 课程编号 | 部门_妈妈 | 状态 | 描述_ar | desc_zh |
---|---|---|---|---|---|
63 | 8542 | 51 | 1 | 测试AR4516 | 测试En4516 |
28 | 8886 | 51 | 1 | 测试AR4516 | 测试En4516 |