Suppose I have a simple MySQL table that looks like this:
CREATE TABLE `my_table` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 8 ) NOT NULL
) ENGINE = MYISAM ;
I want to create two rows that are related to each other. I’ve considered doing it two ways.
First strategy: Adding a “related_to” field to the table.
I am using AUTO_INCREMENT to calculate the ID, I’ll need 5 steps to do this.
- INSERT INTO
my_table(name) VALUES (‘abc’); - Retrieve insert ID (let’s call it $first_id)
- INSERT INTO
my_table(name,related_to) VALUES (‘xyz’, ‘$last_id’); - Retrieve insert ID (let’s call it $second_id)
- UPDATE
my_tableSETrelated_to= ‘$second_id’ WHEREid= ‘$first_id’;
Second strategy: A separate table linking with both IDs. Can do this in 5 steps as well.
- INSERT INTO
my_table(name) VALUES (‘abc’); - Retrieve insert ID (let’s call it $first_id)
- INSERT INTO
my_table(name) VALUES (‘xyz’); - Retrieve insert ID (let’s call it $second_id)
- INSERT INTO
link_table(item1,item2) VALUES (‘$first_id’, ‘$second_id’);
Which way would be best in terms of efficiency, or is there an even more efficient way of doing it that I am missing?
Thanks for your advice.
Using a third column will be more efficient in terms of processing – queries will run slightly faster.
Using a separate relationship will be more efficient in terms of memory usage – your database will occupy slightly less memory.
I’d be tempted to go for the relationship table because it results in a normalized design, although it will be a bit harder to work with. It will avoid any issues you might have where the related_to values become out of sync. For example, A and B are related to each other. A has related_to=B, B has related_to=A. This is duplicate data so requires a bit more management to keep consistent if you use a third column.
Depending on the volume of your data, it’s unlikely that you’ll have any real performance issues with either of these designs (the difference will be in terms of milliseconds), so you should probably take whichever feels more comfortable.