You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL:如何通过另一张表更新目标表的空日期字段?

问题描述

现有以下PostgreSQL表结构及数据:

CREATE TABLE employee
(
    joining_date date,
    employee_type character varying,
    name character varying 
);
insert into employee VALUES
    (NULL,'as','hjasghg'),
    ('2022-08-12', 'Rs', 'sa'),
    (NULL,'asktyuk','hjasg');
    
create table insrt_st (employee_type varchar, dt date);
insert into insrt_st VALUES ('as', '2022-12-01'),('asktyuk', '2022-12-08') 

需要编写一条单独的查询语句,将insrt_st表中的日期值更新到employee表中joining_date字段为NULL的对应记录中。

解决方案

使用PostgreSQL的UPDATE ... FROM语法即可实现关联更新:

UPDATE employee
SET joining_date = insrt_st.dt
FROM insrt_st
WHERE employee.joining_date IS NULL
  AND employee.employee_type = insrt_st.employee_type;
说明
  • 通过employee_type字段关联两张表,确保只更新类型匹配的记录
  • WHERE employee.joining_date IS NULL限定仅处理原表中日期为空的记录,不会覆盖已有有效日期
  • 执行后,employee表中两条joining_date为NULL的记录会被分别更新为2022-12-01和2022-12-08

内容的提问来源于stack exchange,提问作者codeanonym

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:20:30