开发者

How to make proper use of foreign keys

开发者 https://www.devze.com 2023-03-15 07:53 出处:网络
I\'m developing a helpdesk-like system, and I want to employ foreign keys, to make sure the DB structure is decent, but I don\'t know if I should use开发者_开发知识库 them at all, and how to employ th

I'm developing a helpdesk-like system, and I want to employ foreign keys, to make sure the DB structure is decent, but I don't know if I should use开发者_开发知识库 them at all, and how to employ them properly.

Are there any good tutorials on how (and when) to use Foreign keys ?

edit The part where I'm the most confused at is the ON DELETE .. ON UPDATE .. part, let's say I have the following tables

table 'users'
id int PK auto_increment
department_id int FK (departments.department_id) NULL
name varchar

table 'departments'
id int PK auto_increment
name

users.department_id is a foreign key from departments.department_id, how does the ON UPDATE and ON DELETE functions work here when i want to delete the department or the user?


ON DELETE and ON UPDATE refer to how changes you make in the key table propagate to the dependent table. UPDATE means that the key values get changed in the dependent table to maintain the relation, and DELETE means that dependent records get deleted to maintain the integrity.

Example: Say you have

 Users: Name =  Bob, Department = 1
 Users: Name =  Jim, Department = 1
 Users: Name =  Roy, Department = 2

and

 Departments: id = 1, Name = Sales
 Departments: id = 2, Name = Bales

Now if you change the deparments table to modify the first record to read id = 5, Name = Sales, then with "UPDATE" you would also change the first two records to read Department = 5 -- and without "UPDATE" you wouldn't be allowed to make the change!

Similarly, if you deleted Department 2, then with "DELETE" you would also delete the record for Roy! And without "DELETE" you wouldn't be allowed to remove the department without first removing Roy.


You will need foreign keys if you are splitting your database into tables and you are working with a DBMS (e.g. MySQL, Oracle and others). I assume from your tags you are using MySQL.

If you don't use foreign keys your database will become hard to manage and maintain. The process of normalisation ensures data consistency, which uses foreign keys.

See here for foreign keys. See here for why foreign keys are important in a relational database here.

Although denormalization is often used when efficiency is the main factor in the design. If this is the case you may want to move away from what I have told you.

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消