Question

For a project I need to implement row versioning in a MySQL database. After reading about the possible solutions I've chosen to use one table and add a start_date and end_date column, that specify when that version/row was active.

The id column will be the same for multiple versions of a row. Therefore it's no longer unique in the table. Now I'm not sure how to set up the primary key (and other indexes), while keeping auto increment active for the id column.

I see two options. The first one is making id just an index, like this:

CREATE TABLE `thing` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  … other_columns …,
  `start_date` datetime NOT NULL,
  `end_date` datetime DEFAULT NULL,
  KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The other is making id and start_date the primary key, like this:

CREATE TABLE `thing` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  … other_columns …,
  `start_date` datetime NOT NULL,
  `end_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`,`start_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

What would be the best option, especially when taking performance into consideration?


For example, the data would look like this:

id | some_column | start_date | end_date
---|-------------|------------|-----------
1  | Jonathn     | 2013-01-01 | 2013-01-02
1  | Jonathan    | 2013-01-02 | NULL
2  | James       | 2013-02-01 | NULL

In this case I added "Jonathn" but changed it to "Jonathan" later (while keeping the same ID). Later another row ("James") is added.

Était-ce utile?

La solution

Your first example CREATE TABLE statement doesn't have a key*, your second one does. I think your second example is what you want:

CREATE TABLE `thing` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  … other_columns …,
  `start_date` datetime NOT NULL,
  `end_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`,`start_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You may or may not want id to be an auto-incrementing column but that's primarily a question of functionality (do you want to be able to generate incrementing values or just insert them yourself) rather than logical design or performance.

*MySQL unfortunately uses the keyword KEY to designate an index. Keys have to be specified with the UNIQUE KEY or PRIMARY KEY syntax.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top