有没有一种方法可以在MySQL中为记录上最后更新的字段创建时间戳


Is there a way to make a timestamp for the last updated field on a record in MySQL?

有没有办法在mysql表中添加一个标志,在那里我可以在每个记录中放置最后一个更新字段的时间戳和文件名?

您可以通过触发器实现目标。您不必再更新指示更新内容的列。

参见此示例:

drop table if exists foo;
create table foo(a int, b int, c int, 
                 modified timestamp on update current_timestamp, 
                 whichOne varchar(255)
                );
insert into foo (a, b, c) values (1, 2, 3), (4, 5, 6);
drop trigger if exists foomod;
delimiter $$
create trigger foomod before update on foo 
for each row
begin
set @cols = '';
if old.a != new.a then
set @cols = CONCAT(@cols, ', ', 'a');
elseif old.b != new.b then
set @cols = CONCAT(@cols, ', ', 'b');
elseif old.c != new.c then
set @cols = CONCAT(@cols, ', ', 'c');
end if;
set new.whichOne = @cols;
end $$
delimiter ;
select * from foo;

结果:

a   b   c   modified    whichOne
1   2   3       
4   5   6       

update foo set b = 10 where b = 2;
select * from foo;

结果:

a   b   c   modified    whichOne
1   10  3   2013-06-27 12:45:29Z    , b
4   5   6       

当然还有改进的空间,但你明白了,对吧?

ALTER TABLE `YOUR_TABLE_NAME_HERE` ADD LastUpdatedColumns TEXT NULL;
ALTER TABLE `YOUR_TABLE_NAME_HERE` ADD LastUpdated TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

然后当进行更新查询时,它类似于

$fieldsupdated = "field1, field2, field3";
$sql = "UPDATE `YOUR_TABLE_NAME_HERE` SET LastUpdatedColumns='$fieldsupdated';

然后,如果你想在未来报告某一列最后一次编辑的时间/日期,你可以做一些类似的事情

$sql = "SELECT LastUpdated FROM `YOUR_TABLE_NAME_HERE` WHERE LastUpdatedColumns LIKE '%field1%'

有比我想的宽泛的"喜欢"更好的方法,但我今天一辈子都想不起来。