首页 > 解决方案 > MySQL 数据库保留历史更改(如 wiki)

问题描述

我有一个网站让用户更改几个页面,但现在我想以某种方式跟踪这些更改并将它们展示给其他用户。(我猜有点像维基)

这是我目前得到的:

id, title, description, country, language, last_update (and ~20+ more fields)

我正在考虑制作一个带有 ID 和最后一个 history_ID 的主表,然后历史表获取上述所有内容,因此每个新条目都会获得一个新的 history_ID 和所有新条目。

我觉得我可以做得更好。因为使用上面的方法,我最终会得到大量类似的行(只需更改单个字段或字母或其他内容)。

有什么建议么?谢谢!

标签: mysqldatabasedatabase-design

解决方案


我认为你的想法是正确的。您需要两个表,它们应该类似于:

create table page (
  id bigint primary key not null,
  title varchar(100) not null,
  -- More columns here.
  -- The last version of the content column can added here as redundancy,
  --   for performance reasons.
  last_version_id bigint, -- allows null
);

create table page_version (
  id bigint primary key not null,
  content mediumtext not null,
  page_id bigint not null,
  constraint fk_pv_page foreign key (page_id)
    references page (id)
);

alter table page add 
  constraint fk_page_version foreign key (last_version_id)
    references page_version (id);

可以在表格中添加最后一个版本的内容列page(将是多余的)以提高读取/显示页面时的性能。

阅读页面通常比更新它们更常见,因此冗余可以使您的网站更快。

请注意,该列last_version_id允许空值,因此您实际上可以在 MySQL 中插入/更新一行(不实现约束检查可延迟性)。


推荐阅读