【问题标题】:update NULL values of left joint table in Postgres在 Postgres 中更新左连接表的 NULL 值
【发布时间】:2020-05-21 02:56:43
【问题描述】:

我的数据库文档和位置中有这两个表。

select * from  Document     

id  locid   loccode
1   1010    30
2   2020    30
3   3030    30
4   4040    40

select * from location

locid   loccode date    Status
1010    30  20-10-2019  A
2020    30  20-10-2019  A
3030    40  20-10-2019  A
4040    40  20-10-2019  A
6060    30  20-10-2019  A
7070    40  20-10-2019  A
8080    30  20-10-2019  D
9090    40  20-10-2019  D

我想更新位置表中的状态,其记录(左连接空值)不可用文档。 我尝试以下查询,但需要更多时间。

update location 
set status='D' 
from location A 
left join document B on A.locid=B.locid and A.loccode=B.loccode  
where b.id is NULL;

请帮我解决一下

【问题讨论】:

    标签: sql postgresql join sql-update query-optimization


    【解决方案1】:

    我会推荐not exists

    update location 
    set status = 'D' 
    where not exists (
        select 1 
        from document d
        where d.locid = location.locid and d.loccode = location.loccode
    )
    

    为了提高性能,您需要在document(locid, loccode) 上建立索引,因此子查询执行得很快。 location(locid, loccode) 上的索引也可能有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-29
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多