2017-04-21 81 views
0

下面是我創建的表。創建一個觸發器將舊數據插入到新表中

USE my_guitar_shop; 

DROP TABLE IF EXISTS Products_Audit; 

CREATE TABLE Products_Audit ( 
audit_id INT PRIMARY KEY, 
category_id INT REFERENCES categories(category_id), 
product_code VARCHAR (10) NOT NULL UNIQUE , 
product_name VARCHAR (255) NOT NULL, 
list_price INT NOT NULL, 
discount_percent INT NOT NULL DEFAULT 0.00 , 
date_updated DATETIME NULL); 

創建名爲products_after_update的觸發器。在更新行後,此觸發器應將有關產品的舊數據插入到Products_Audit表中。然後,用適當的UPDATE語句測試這個觸發器。

這是我創建的觸發器,但數據沒有顯示在Products_Audit表中顯示爲全部爲空。

USE my_guitar_shop; 

DROP TRIGGER IF EXISTS products_after_update; 

DELIMITER $$ 

CREATE TRIGGER products_after_update 
BEFORE UPDATE ON products 
FOR EACH ROW 
BEGIN 
    INSERT INTO products_audit (audit_id, product_id, category_id, product_code, 
    product_name, list_price, discount_percent, date_updated) 

    SELECT audit_id, products.product_id, products.category_id, products.product_code, 
    products.product_name,products.list_price, products.discount_percent, date_updated 

    FROM products JOIN products_audit 
    ON products_audit.audit_id = (SELECT audit_id FROM inserted); 
END $$ 

DELIMITER ; 

編輯與INSERT INTO

USE my_guitar_shop; 

    DROP TRIGGER IF EXISTS products_after_update; 

    DELIMITER $$ 

    CREATE TRIGGER products_after_update 
BEFORE UPDATE ON products 
FOR EACH ROW 
    BEGIN 

    INSERT INTO products_audit (audit_id, product_id, category_id,product_code, 
    product_name, list_price, discount_percent, date_updated) 

    VALUES (OLD.audit_id, OLD.product_id, OLD.category_id, OLD.product_code, 
    OLD.product_name, OLD.list_price, OLD.discount_percent, OLD.date_updated) 

    DELIMITER ; 

回答

0

你過分複雜的插件。作爲triggers MySQL文檔說:

在一個UPDATE觸發器,您可以使用OLD.col_name指一個行的列 它更新之前和NEW.col_name指該行的列 更新後。

因此,在插入中使用OLD.column_name格式。另外,我想設置audit_id場自動增量和離開它插入的:

INSERT INTO products_audit (product_id, category_id, product_code, 
product_name, list_price, discount_percent, date_updated) 
VALUES (OLD.product_id, OLD.category_id, OLD.product_code, 
OLD.product_name, OLD.list_price, OLD.discount_percent, OLD.date_updated) 
+0

我會做同樣的產品來自JOIN products_audit ON products_audit聲明?當我添加你的插入時,我得到這個錯誤CREATE TRIGGER products_after_update在更新之前產品FOR EACH ROW BEGIN INSERT INTO products_audit(audit_id,product_id,category_id,product_code,product_name,list_price,discount_percent,date_updated)VALUES(OLD.audit_id,OLD.product_id, OLD.category_id,OLD.product_code,OLD.product_name,OLD.list_price,OLD.discount_percent,OLD.date_updated)FROM products JOIN products_audit – Harvey

+0

您沒有明白:完全不需要選擇零件! – Shadow

+0

我刪除了SELECT部分​​,但它顯示我在最後的VALUES的括號中有一個語法錯誤。 – Harvey

相關問題