Thursday 9 May 2013

What is Foreign Key?


What's in a Database?
a database is a container that holds tables and other SQL structures related to those tables.


An easier way to diagram account table

Every one having different hobbies. Remove the hobbies column and put it in its own table

Add name column that will let us identify which hobbies belong to which person in the account table.
Linking two tables in a diagram

Connecting Two tables

The problem we're trying to use name field to somehow let use connect the two tables. But what if two people in the account table have the same name ?

Foreign Key Facts :
A foreign key can have a different name that the primary key it comes form.
The primary key used by a foreign key is also known as a parent key. the table where the primary key is from is knows as a parent table.
The foreign key can be used to make sure that the rows in on table have corresponding rows in another table.
Foreign key values can be null, even though primary key values can't.
Foreign key don't have to be unique.



CREATE TABLE account(
user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20),
email VARCHAR(30),
birthday DATE,
gender VARCHAR(10),
city VARCHAR(30));




CREATE TABLE hobbies(
hob_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,hobby VARCHAR(100) NOT NULL,
user_id INT NOT NULL,
CONSTRAINT account_user_id_fK
FOREIGN KEY(user_id)
REFERENCES account(user_id));




3 comments:

  1. Thanks for all the simplified version dude..

    ReplyDelete
  2. A Master Key system is complex and not every locksmith is capable of properly maintaining the integrity of the system. Here are some things to consider when choosing the right locksmith:duplicate key maker near me

    ReplyDelete
  3. Then there are key making systems and key blanks. Since the locksmith can use the key maker to carve and shape various kinds of key designs and structures, therefore it is a tool of versatile use for him.key copy near me

    ReplyDelete