1

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

4

2 回答 2

1

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

看这个例子:

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       

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

于 2013-06-27T10:48:31.870 回答
0
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%'

有比我认为的广泛的 LIKE 更好的方法,但我今天无法想到它。

于 2013-06-27T10:27:21.337 回答