如何基于来自同一表的数据更新表列(使用联接)

时间:2019-07-10 17:03:09

标签: mysql sql

我正在尝试更新发票表的每一行以保存该发票的税额。这是通过获取与供应商关联的税收百分比并将其乘以发票金额(显然)得出的。我的问题是我试图用来自与其他表连接的同一表中的数据更新表。目前,我的查询显示如下:

Error Code: 1093. Table 'tblVendorInvoices' is specified twice, both as a target for 'UPDATE' and as a separate source for data

当我删除WHERE语句时

Error Code: 1054. Unknown column 'a.VENDORINVOICEID' in 'where clause'

使用WHERE

这是我的查询:

UPDATE tblVendorInvoices SET VdrTaxAmount = 
(SELECT round(VdrInvoiceAmount*TaxAmount,2) FROM tblVendorInvoices a
LEFT JOIN tblVendors ON a.VendorName = tblVendors.VendorID
LEFT JOIN tblTax on tblVendors.vdrtaxid = tblTax.TAXID)
WHERE a.VENDORINVOICEID = tblVendorInvoices.VENDORINVOICEID;

3 个答案:

答案 0 :(得分:0)

这应该有效

UPDATE tblVendorInvoices SET VdrTaxAmount = c.Amount
from
(SELECT VENDORINVOICEID,round(VdrInvoiceAmount*TaxAmount,2) Amount FROM tblVendorInvoices a
LEFT JOIN tblVendors ON a.VendorName = tblVendors.VendorID
LEFT JOIN tblTax on tblVendors.vdrtaxid = tblTax.TAXID)c
WHERE c.VENDORINVOICEID = tblVendorInvoices.VENDORINVOICEID;

答案 1 :(得分:0)

在MySQL中,使用相关子查询。我认为这是您想要的逻辑:

UPDATE tblVendorInvoices i
    SET VdrTaxAmount = 
        (SELECT round(VdrInvoiceAmount*TaxAmount,2)
         FROM tblVendors v JOIN
              tblTax t
              ON v.vdrtaxid = t.TAXID
         WHERE i.VendorID = v.VendorID
        );

答案 2 :(得分:0)

尝试一下

UPDATE tblVendorInvoices SET VdrTaxAmount = 
(SELECT round(VdrInvoiceAmount*TaxAmount,2) 
FROM tblVendorInvoices as A
LEFT JOIN tblVendors as V ON a.VendorName = V.VendorID
LEFT JOIN tblTax on V.vdrtaxid = tblTax.TAXID)
WHERE A.VENDORINVOICEID = V.VENDORINVOICEID;

您收到该错误,是因为您没有在where语句中区分要使用的表和列:     其中a.VENDORINVOICEID = tblVendorInvoices.VENDORINVOICEID; 您正在使用相同的表和列。 您可能还会查看第一个join语句,因为您可能正在尝试连接字符串和INT,但这将无法正常工作。您需要联接两个具有相同数据类型的列。我不知道您的每一列都有什么类型的数据。