Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of relationships between tables in sql?

I made three tables.
Table1=users.And the column names are userid (auto_increment) and username.
Table2=hobbies. column names are hobbyid (auto_increment) and hobbyname.
Table3=users_hobbies. column names are FK_userid and FK_hobbyid.

Now whenever I register new user and his/her hobbies from a html form, I select the
corresponding userid and hoobyid
that is generated from table 1 and table 2
and insert them to table 3 using query

So what is the use of relationship, if I create it between table 1 and 3 and table 2 and 3?
Will the corresponding userid and hobbyid automatically go to table 3 without using query?

like image 831
Santosh Avatar asked Dec 26 '22 22:12

Santosh


1 Answers

No, the userid and hobbyid won't go automatically anywhere.

The major point of relationships or rather constraints is to enforce data integrity. That means you shouldn't be able to add an entry containing id 2, 2 into the users_hobbies table without a user with id 2 and a hobby with id 2.

In order to keep this integrity you can also specify cascadings. (Depending on the Database system, I hardly work with mysql, so I am not sure about that).

That means, you can specify that all users_hobbies for user with id 1 are deleted if the user himself is deleted.

like image 134
mfussenegger Avatar answered Jan 18 '23 23:01

mfussenegger