I was to verify the ideal way to store in the database an ID of the format:
[type] - [year] - [auto-increment]
wherein the auto-increment
field is based on the type
.
Here are some examples:
ABC-2016-1
ABC-2016-2
XYZ-2016-1
ABC-2016-3
XYZ-2016-2
AAA-2016-1
AAA-2016-2
AAA-2016-3
as we can see, ABC
, XYZ
and AAA
have different auto-increment IDs that differ based on which came first.
What I thought of the table structure is this:
TABLE my_table (
id INT UNSIGNED AUTO_INCREMENT UNIQUE PRIMARY KEY,
type ENUM('ABC', 'XYZ', 'AAA') NOT NULL,
year INT UNSIGNED NOT NULL,
order INT UNSIGNED NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8;
just store the first two, and during saving to DB, I search my_table
for all enum
s and get the maximum ie (CI-style, pseudocode only):
$this->db->select_max('order');
$this->db->where('type', $type);
$order = $this->db->get('my_table');
$data_to_save['order'] = $order + 1;
I am not confident with doing the increment every time, is there a better way to deal with this?
Should I just create multiple tables for my types
? Say:
TABLE abc (
id INT UNSIGNED AUTO_INCREMENT UNIQUE PRIMARY KEY,
year INT UNSIGNED NOT NULL,
order INT UNSIGNED NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8;
TABLE xyz (
id INT UNSIGNED AUTO_INCREMENT UNIQUE PRIMARY KEY,
year INT UNSIGNED NOT NULL,
order INT UNSIGNED NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8;
TABLE aaa (
id INT UNSIGNED AUTO_INCREMENT UNIQUE PRIMARY KEY,
year INT UNSIGNED NOT NULL,
order INT UNSIGNED NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8;