首页 > 解决方案 > SQL:使用子查询与 FROM 从列表更新

问题描述

我很好奇这两个示例之间的性能差异,以及它们在 postgreSQL 中是否真正等效。当我使用列表而不是使用 FROM 进行分配时,似乎唯一可能出现性能差异的地方。

这些示例基于PostgreSQL 练习网站,用于更新计算提示

使用列表的示例:

update cd.facilities
    set (membercost, guestcost) = (select membercost1.1, guestcost1.1 from cd.facilities where facid = 0)
    where facid = 1

FROM 示例:

update cd.facilities fac
    set
        membercost = fac2.membercost1.1,
        guestcost = fac2.guestcost1.1
    from (select * from cd.facilities where facid = 0) fac2
    where fac.facid = 1

标签: sqlpostgresqlquery-optimization

解决方案


您实际上应该尝试查询。我希望性能是相似的。例如,如果可用,两者都会使用索引。

但是,您可以在没有子查询的情况下编写它:

update cd.facilities f1
    set membercost = f0.membercost1.1,
        guestcost = f0.guestcost1.1
    from  cd.facilities f0
    where fo.facid = 0 and
          f1.facid = 1;

对于所有这些,我建议在facilities(facid). facid如果是主键,您可能已经拥有它。


推荐阅读