Why do I need to use foreign key if I can use WHER

2019-01-21 19:03发布

A beginners' question about foreign key in MySQL.

In w3school it says,

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

And also there is WHERE,

WHERE id = page_id

So if I can use WHERE for linking the tables, what is the main purpose of having foreign key?

10条回答
迷人小祖宗
2楼-- · 2019-01-21 19:26

So if I can use WHERE for linking the tables, what is the main purpose of having foreign key?

Because WHERE clause is not limited to equijoins on foreign keys.

Say, if you have a table which describes price ranges and discounts, you use this complex condition to join the tables:

SELECT  *
FROM    Goods
JOIN    PriceRange
ON      PriceRange.Price =
        (
        SELECT  MAX(Price)
        FROM    PriceRange
        WHERE   PriceRange.Price <= Goods.Price
        )

You cannot link these table with a foreign key relationship, but you can easily join them.

See this entry in my blog for more details:

The pk-to-pk binding, though, is still important. A FOREIGN KEY can assure you that the entitie you are linking are described by your relational model.

With a FOREIGN KEY-backed design, you cannot declare a relationship to an entity whose PRIMARY KEY is absent in the table that describes that entity.

SQL Server can even take this fact into account and optimize the certain types of queries.

Say, this query:

SELECT  f.*
FROM    t_foreign f
WHERE   f.pid IN
        (
        SELECT  id
        FROM    t_primary p
        )

will not even look into t_primary if the FOREIGN KEY relationship is defined between t_foreign and t_primary.

See this article for more details:

查看更多
Viruses.
3楼-- · 2019-01-21 19:28

Maintaining referential integrity and indexing.

查看更多
叛逆
4楼-- · 2019-01-21 19:29

First of all. Good Question !!

MySql is an RDBMS - Relational DBMS, so all the entities (tables) are related by an column.

EMPLOYEE - EMPID EMPNAME DEPTID

DEPARTMENT - DEPTID DEPTNAME

DEPTID is foriegn key in the EMPLOYEE table and primary key in the DEPARTMENT table.

This relation is imaginary relation of objects just an consideration or kind of designing for structuring data in a easy way to retrieve in future. NOT A PHYSICAL RELATION (because its a programming language)

In order to retrive that data, we need few syntax and described by the Creator of SQL.

SELECT * from EMPLOYEE

SELECT * FROM DEPARTMENT

SELECT * FROM EMPLOYEE WHERE DEPTID = 5

Here we have realted the two tables imaginary for our convinent, but for the required result we used this syntax WHERE DEPTID = 5.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-21 19:33

I have another good reason to add the key relationships to your database. There are various code generators that use this information to generate an object model from your database. One notable pattern in common use is the ActiveRecord pattern. Without key relationships, the ActiveRecord pattern would not know how your database entities are related so it would generate a much less useful object model.

Code generation is not appropriate for every software project. But, it is helpful on a large number of projects. If you aren't using code generation you owe it to yourself to at least look into it.

查看更多
狗以群分
6楼-- · 2019-01-21 19:35

It's not strictly needed for the query, it's true. It exists for several reasons:

  1. As a constraint on the table to stop you inserting something that doesn't point to anything;
  2. As a clue for the optimizer; and
  3. For historical reasons where is was more needed.

(1) is probably the important one of the three. This is called referential integrity. It means that if there is a value in a foreign key there will be a corresponding record with that value as a primary key in the parent table.

That being said, not all databases support referential integrity (eg MySQL/MyISAM tables) and those that do don't necessarily enforce it (for performance reasons).

查看更多
唯我独甜
7楼-- · 2019-01-21 19:38

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.

查看更多
登录 后发表回答