![](/img/trans.png)
[英]How do I write a mysql query to get a list of records from one table with columns concatenated from multiple other tables
[英]In mySQL, how do I make a Trigger so that one table keeps a change log from ALL other tables?
我的想法是有一個名為“changelog_table”的表,其中包含以下列:
updated_table //the table being updated
updated_column //the column being updated
updated_row //the id of the row being updated
updated_content //this is what they updated the field to
updated_user //the user who updated
updated_datetime //the timestamp it was updated
我認為這是我真正想要的最小值和最大值,但我可能錯了。 另外......經過幾周的閱讀后,我不明白如何在我的觸發器中存儲變量(如“正在更新哪個表”和“正在更新哪個列”等等)。
因此,假設我有一個名為“foo_table”的表,其中一列“bar_column”,行“58008”,正在被用戶“peter_griffin”更新為“這是新內容”,時間為12/30 / 2013年中午。
什么觸發器可以捕捉到這樣的樣子?
您需要在每個表上為UPDATE
創建單獨的觸發器(如果需要,也需要為INSERT
和DELETE
)。 他們每個人都可以調用與實際日志記錄相同的存儲過程。
觸發器可以向存儲過程傳遞一個參數,該參數包含正在執行操作的表的名稱(因為觸發器是特定於表的,它將知道這一點 - 它必須是硬編碼的); 要檢測哪些列已更新,您需要在每個觸發器中對相應表中每列的NEW.column
和OLD.column
進行比較。
例如:
CREATE TRIGGER upd_tbl_name AFTER UPDATE ON tbl_name FOR EACH ROW
CALL AuditLog('UPDATE', 'tbl_name', NEW.id, CONCAT_WS(',',
IF(NEW.columnA <=> OLD.columnA, NULL, CONCAT('columnA:=', NEW.columnA)),
IF(NEW.columnB <=> OLD.columnB, NULL, CONCAT('columnB:=', NEW.columnB)),
-- etc.
));
CREATE PROCEDURE AuditLog(
Action VARCHAR(10),
TableName VARCHAR(64),
RowID INT,
Columns TEXT,
)
INSERT INTO changelog_table VALUES (
Action,
TableName,
RowID,
Columns
USER(),
NOW(),
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.