I’m very confused in creating Tables in MySQL because I read some PHP tutorials and the authors create two tables in their database and then linking them up later in PHP using joins.
Here’s an example I got from an article..
Here the author created the table users and groups.
CREATE TABLE users (
id int(8) NOT NULL auto_increment,
name varchar(255) NOT NULL default '',
pass varchar(255) NOT NULL default '',
PRIMARY KEY (id)
) TYPE=InnoDB;
CREATE TABLE groups (
uid int(8) NOT NULL default '0',
grp varchar(255) NOT NULL default ''
) TYPE=InnoDB;
When I look at it, isn’t the groups table not necessary? I mean I can just create the table this way:
CREATE TABLE users (
id int(8) NOT NULL auto_increment,
name varchar(255) NOT NULL default '',
pass varchar(255) NOT NULL default '',
grp varchar(255) NOT NULL default ''
PRIMARY KEY (id)
) TYPE=InnoDB;
In this way, I can just query the database and I don’t need to join the two tables together at all.
So what’s the purpose of creating two tables and not one? Please explain to me why linking together two tables is better than one.
I a lot of authentication systems 1 user can have multiple groups. Therefore 2 tables are necessary. If you want to have a good idea how to design your tables than you can have a read on database normalization.
even beter would be if you create a table for groups, a table for users, and a table for users in groups. This is because it’s common to have multiple users in a group and users can have multiple groups (many to many relation). Many to many relations in relational databases are not possible. Therefor you need the extra table.
An other advantage of this system is that if you decide to change the group name than you don’t need to change that name for each user. You can just change the name once and it’s changed for all users.
You get something like this.
You can also have a look at FCO-IM which is a more complicated method to design databases compared to ERM, but might be handy for bigger and more complicated databases.