What exactly is a foreign key?

2019-01-22 15:20发布

Ok. So I know what a primary key in DB is. If you have a table in a database, a primary key is a single value that is unique to each row in your table. For example:

id   | name    | whatever
-------------------------
1      Alice     ....
2      Bob       ....
45     Eve       ....
988    ....      ....

So I need a good, simple example to explain what exactly a foreign key is. Because I just don't get it :)


Edit: OK it's pretty easy, I guess I was over-complicating the problem.

So one final question, the only restriction on foreign keys is that it they are a valid primary key value in the table I am referring to?

8条回答
你好瞎i
2楼-- · 2019-01-22 15:59
id   | name    | whatever | countryid
-------------------------------------
1      Alice     ....       13
2      Bob       ....       42
45     Eve       ....       1
988    ....      ....       2

id   | countryid
----------------
1      Japan
2      Spain
13     Norway
42     Italy

The foreign key points from the person table (first) to a row in the country table (second)

查看更多
乱世女痞
3楼-- · 2019-01-22 16:01

Let's say you have another field, which is the home city:

id   | name    | city
-------------------------
1      Alice     San Francisco
2      Bob       New York
45     Eve       New York
988    Bill      San Francisco

Now, it does not make sense to repeat the same cities in many rows. This could lead you to typos, excessive space usage, difficulties to bring up results among other problems. So you use a foreign key:

id   | name    | fk_city
-------------------------
1      Alice     1
2      Bob       2
45     Eve       2
988    Bill      1

home city table:

id   | name
-------------------------
1    | San Francisco
2    | New York

Hope it makes things clearer for you. :-)

Update: about your final question: Yes. :-)

查看更多
登录 后发表回答