[英]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.