首页 > 解决方案 > 如何在postgresql的join中的select语句之一中使用列值

问题描述

我更新sitename如下。但是然后我需要在另一个查询中使用levelindexfrom a,该查询将与第一个查询连接。

update billofquantity_temp a
    set sitename = b.boqitemname 
from (
 select a.* from
 (
 select levelindex,productno,boqitemid,boqitemname,fileid from billofquantity_temp
                where productno ='' and levelindex !='' //first query
 ) a
    join 
 (
 select distinct substring(levelindex,1,length(a.levelindex) lblindex from billofquantity_temp
               where boqitemid !='' and levelindex !='' 
               and length(levelindex) > 2
 ) b    on a.levelindex=b.lblindex // second query 
) b
where a.levelindex=b.levelindex; 

我需要在第二个查询中使用 a.levelindex 来获取它的长度的子字符串。但这会引发错误invalid reference to FROM-clause entry for table "a"

有没有其他方法可以在加入查询 1 in 2 时使用该列?

更新:根据 kims 的回答,我可以完成选择,但有错误 syntax error at c.a.levelindex。即使使用 . 也会引发错误c.levelindex。对查询的轻微修改没有错误,但没有发生预期的更新。相反,只有一个特定值被更新。以下是删除错误的更新查询

 update billofquantity_temp d
 set sitename = c.boqitemname
 from (
      select *  from (
            select levelindex, boqitemname from billofquantity_temp
            where productno = '' and levelindex != '' -- first query
                     ) a
                join (
            select distinct levelindex lblindex from billofquantity_temp
            where boqitemid != '' and levelindex != '' and length(levelindex) > 2   ) b
on a.levelindex = substring(b.lblindex, 1, length(a.levelindex)) -- second query
      ) c 
       where d.levelindex = c.lblindex;

标签: postgresqlinner-join

解决方案


lblindex将子选择之外的计算移至on子句:

update billofquantity_temp d
set sitename = c.boqitemname
from (
    select *
    from (
        select levelindex, boqitemname
        from billofquantity_temp
        where productno = '' and levelindex != '' -- first query
    ) a
    join (
        select distinct levelindex
        from billofquantity_temp
        where boqitemid != '' and levelindex != '' and length(levelindex) > 2     
    ) b
    on a.levelindex = substring(b.levelindex, 1, length(a.levelindex)) -- second query
) c 
where d.levelindex = c.a.levelindex
;

我还使用了candd以避免混淆使用aandb两次,添加了一个缺失的),并从select.


推荐阅读