4

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Santosh
  • 1,871
  • 1
  • 19
  • 36
  • No, a foreign key relationship from table 3 verifies that the user record in table 1 and the hobby record in table 2 exist before allowing an entry to be created in table 3... otherwise you end up with lots of orphaned records clogging up your table 2, so it's an automatic validation; and if you do a cascade delete on table 1, it will automatically delete any related table 3 records for you – Mark Baker Jun 17 '12 at 16:58
  • thanks! i was really having problems of orphaned records when updating the user details...will now use relationship.. – Santosh Jun 18 '12 at 17:37

1 Answers1

10

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.

mfussenegger
  • 3,931
  • 23
  • 18