2014-04-02 35 views
0

如何编写查询以更新具有两个左连接的表。下面是MSSQL中的一个查询,我想将它转换为postgresql。请帮忙。用postgresql中的左连接更新

Update T1 Set 
      T1.Amount = (T1.Amount - T2.Disc) + ((DT1.N_Amount)/2) 

    From @Before T1 
    Left Join @Before T2 On T1.ID = T2.ID 
    Left Join @DiscTable DT1 On T1.PurchID = DT1.Purch_ID 

回答

3

这是可能的Postgres里也the main difference is

Note that the target table must not appear in the from_list , unless you intend a self-join (in which case it must appear with an alias in the from_list).

您的查询转换:

UPDATE "Before" "T1" 
SET "T1"."Amount" = ("T1"."Amount" - "T2"."Disc") + (("DT1"."N_Amount")/2) 
FROM "Before" "T2" 
LEFT JOIN "DiscTable" "DT1" ON "T1"."PurchID" = "DT1"."Purch_ID" 
WHERE "T1"."ID" = "T2"."ID" 

但为什么在这里使用自加入? (如果"ID"是主键),我想你可以achive你的目标可以简单地使用:

UPDATE "Before" "T1" 
SET "T1"."Amount" = ("T1"."Amount" - "T1"."Disc") + (("DT1"."N_Amount")/2) 
FROM "DiscTable" "DT1" 
WHERE "T1"."PurchID" = "DT1"."Purch_ID" 

编辑about quoting

Quoting an identifier also makes it case-sensitive, whereas unquoted names are always folded to lower case. For example, the identifiers FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo" and "FOO" are different from these three and each other. (The folding of unquoted names to lower case in PostgreSQL is incompatible with the SQL standard, which says that unquoted names should be folded to upper case. Thus, foo should be equivalent to "FOO" not "foo" according to the standard. If you want to write portable applications you are advised to always quote a particular name or never quote it.)

+0

但它显示错误:无效引用FROM子句表“t1”的条目 – user1690835

+0

如果您在表格/列名称中混合使用大小写字母,请使用无处不在或无处引用。如果您不引用postgresql标识符,它将转换为小型大写字母以实现iso sql不区分大小写。 http://www.postgresql.org/docs/9.3/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS – pozs