SQLITE3 - 如何使用主键在另一个表上INSERT期间从表中进行选择以查找相关信息

时间:2017-06-28 12:28:56

标签: sql sqlite

我正在尝试创建以下触发器,以便每次在tblInvoiceItems中的该发票ID下创建新项目时更新tblInvoices的父发票记录。要更新的字段是小计,税金和总计。

CREATE TRIGGER tblInvoiceItems_insert AFTER INSERT ON tblInvoiceItems
BEGIN
    INSERT tblInvoices (numberOfItems, subTotal, taxes, total)
    VALUES (numberOfItems + NEW.quanity, subTotal + NEW.charge,
    (SELECT taxRate FROM tblTaxRates WHERE tblInvoiceItems.taxRateID = tbltaxRates.taxRateID)
     * (subTotal + NEW.charge),
    (SELECT taxRate FROM tblTaxRates WHERE tblInvoiceItems.taxRateID = tblTaxRates.taxRateID)
     * (subTotal + NEW.charge) + subTotal + NEW.charge)
    WHERE invoiceID = NEW.invoiceID;
    INSERT INTO tblLogs (affectedObject, userID, eventDescription, eventDescription, dtOccurred) VALUES ("INI" || REPLACE(PRINTF("%8s", NEW.itemID), "0"), 1, "Item added to invoice.", CURRENT_TIMESTAMP);
END;

错误SQLite3给了我: 错误:靠近第1行:接近"(":语法错误

我不能为我的生活弄清楚错误是什么或者是哪个开括号。

1 个答案:

答案 0 :(得分:1)

嗯,你不能将INSERT INTO .. VALUESINSERT INTO .. SELECT FROM构造在一起,而你当前正在做的就是错误。你应该将它改为下面的(语法)虽然你的WHERE没有意义WHERE taxRateID = tblTaxRates.taxRateID ..不确定为什么你要加入同一个表(看起来不像self join)< / p>

INSERT INTO tblInvoices (numberOfItems, subTotal, taxes, total)
SELECT numberOfItems + NEW.quanity, subTotal + NEW.charge,
taxRate ,
taxRate 
FROM tblTaxRates 
WHERE taxRateID = tblTaxRates.taxRateID)
 * (subTotal + NEW.charge) + subTotal + NEW.charge)
AND invoiceID = NEW.invoiceID;