简体   繁体   English

在postgresql中使用左连接进行更新

[英]update with left join in postgresql

How to write a query for updating a table that has two left joins. 如何编写查询以更新具有两个左连接的表。 Below is a query in MSSQL, I want to convert it into postgresql. 下面是MSSQL中的一个查询,我想把它转换成postgresql。 Please help. 请帮忙。

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

This is possible in postgres too, the main difference is 这在postgres中也是可能的, 主要区别在于

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 ). 请注意,目标表不得出现在from_list ,除非您打算进行自from_list (在这种情况下,它必须在from_list显示别名)。

Your query converted: 您的查询已转换:

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"

But why use self-join here? 但为什么要在这里使用自联? (if "ID" is the primary key) I think you can achive your goal simpler, with: (如果"ID"是主键)我认为你可以更简单地实现你的目标:

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

Edit : 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. 例如,PostgreSQL认为标识符FOO,foo和“foo”是相同的,但是“Foo”和“FOO”与这三个和彼此不同。 (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.) (在PostgreSQL中将不带引号的名称折叠为小写与SQL标准不兼容,后者表示不带引号的名称应折叠成大写。因此,根据标准,foo应相当于“FOO”而不是“foo”。如果如果您想编写便携式应用程序,建议您始终引用特定名称或从不引用它。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM