如果我可以在哪里使用,为什么我需要使用外键?

[英]Why do I need to use foreign key if I can use WHERE?


A beginners' question about foreign key in MySQL.

关于MySQL中外键的一个初学者的问题。

In w3school it says,

在w3school它说,

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?

如果我可以使用WHERE来链接表,那么使用外键的主要目的是什么?

10 个解决方案

#1


37  

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. 作为对表格的约束来阻止你插入一些不指向任何东西的东西;
  3. As a clue for the optimizer; and
  4. 作为优化器的线索;和
  5. For historical reasons where is was more needed.
  6. 出于历史原因,我们更需要is。

(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.

(1)可能是三者中最重要的一个。这被称为引用完整性。这意味着,如果外键中有一个值,则会有一个相应的记录,该记录的值作为父表中的主键。

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).

尽管如此,并不是所有数据库都支持引用完整性(如MySQL/MyISAM表),而那些不支持引用完整性的数据库(出于性能原因)。

#2


7  

The Foreign is used for referential integrity.

外置用于指称完整性。

See An introduction to foreign keys and referential integrity in MySQL

在MySQL中可以看到外键和引用完整性的介绍。

#3


5  

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

如果我可以使用WHERE来链接表,那么使用外键的主要目的是什么?

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

因为WHERE子句不限于外键上的等联接。

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.

不过,pk-to-pk绑定仍然很重要。外键可以确保您所链接的实体是由关系模型描述的。

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.

SQL Server甚至可以考虑这个事实并优化某些类型的查询。

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.

如果在t_foreign和t_primary之间定义了外键关系,那么甚至不需要查看t_primary。

See this article for more details:

详情请参阅本文:

#4


2  

Maintaining referential integrity and indexing.

维护引用完整性和索引。

#5


1  

The primary purpose of a WHERE clause is to limit the rows returned by the query. See SELECT Syntax.

WHERE子句的主要目的是限制查询返回的行。看到选择语法。

Primary key/Foreign key relationships maintain referential integrity and with proper indexing increase the performance of queries. (See Pete OHanlon's explanation, above and JOIN Types)

主键/外键关系保持引用完整性,适当的索引可以提高查询的性能。(见上面Pete OHanlon的解释和JOIN类型)

#6


1  

the RESTRICT operator (WHERE) has nothing to do with referential constraints!

限制操作符(WHERE)与引用约束无关!

quote from C. J. Date's Relational Database Dictionary

引用C. J. Date的关系数据库字典

foreign key Let R1 and R2 be relvars, not necessarily distinct, and let K be a key for R1. Let FK be a subset of the heading of R2 such that there exists a possibly empty sequence of attribute renamings that maps K into K' (say), where K' and FK contain exactly the same attributes. Then FK is a foreign key

外键让R1和R2为relvars,不一定是不同的,让K为R1的键。让FK是R2标题的子集,这样就存在一个可能为空的属性重命名序列,它将K映射到K'(比方说),其中K'和FK包含完全相同的属性。那么FK就是外键

referential integrity Loosely, the rule that no referencing tuple is allowed to exist if the corresponding referenced tuple doesn't exist. More precisely, let FK be some foreign key in some referencing relvar R2; let K be the corresponding key in the corresponding referenced relvar R1, and let K' be derived from K as described under foreign key. Then the referential integrity rule requires there never to be a time at which there exists an FK value in R2 that isn't the K' value for some (necessarily unique) tuple in R1 at the time in question. R1 and R2 here are the referenced relvar and the referencing relvar, respectively, and the constraint between them is a referential constraint.

引用完整性松散,如果对应的引用元组不存在,则不允许存在引用元组。更准确地说,让FK是某个引用relvar R2中的某个外键;让K为相应的参考relvar R1中的对应键,并让K从K中导出,按照外键描述。然后引用完整性规则要求,在R2中不存在FK值,而在R1中的某些(必然是唯一的)元组中,FK值不是K值。R1和R2分别是引用的relvar和引用的relvar,它们之间的约束是引用约束。

Examples: In relvar SP, {S#} and {P#} are foreign keys corresponding to the keys {S#} and {P#} in relvars S and P, respectively. Note that the key in the referenced relvar that corresponds to a given foreign key is not required to be a primary key specifically.

示例:在relvar SP中,{S#}和{P#}是分别对应于relvars S和P中的键{S#}和{P#}的外键。请注意,与给定的外键对应的引用relvar中的键不需要是特定的主键。

#7


1  

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.

我有另一个很好的理由将键关系添加到数据库中。有各种代码生成器使用这些信息从数据库生成对象模型。ActiveRecord模式是一种常见的模式。如果没有键关系,ActiveRecord模式将不知道数据库实体是如何关联的,因此它将生成一个用处不大的对象模型。

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.

代码生成并不适合每个软件项目。但是,它对大量的项目是有帮助的。如果您不使用代码生成,那么您至少应该自己研究它。

#8


0  

A Foreign Key is used to maintain referential integrity, while a WHERE clause is used to join tables together in a SQL operation such as a select. The where clause can operate across multiple tables, but it is purely there as a filter.

外键用于维护引用完整性,而WHERE子句用于在SQL操作(如select)中将表连接在一起。where子句可以跨多个表操作,但它只是作为一个过滤器存在。

Strictly speaking, you can get away without referential integrity, but it's not a good idea. Without referential integrity, you end up relying on your client application not incorrectly deleting or updating something at one end of a relationship chain that would have a knock on effect on the data, e.g. changing a key value to point to one that's not there.

严格地说,你可以在没有参照完整性的情况下逃脱,但这不是一个好主意。如果没有引用完整性,您最终将依赖于您的客户端应用程序不正确地删除或更新关系链的一端的某些内容,这些内容可能会对数据产生影响,例如,将一个键值更改为指向一个不存在的值。

Referential integrity is a great way of ensuring that related data is held in a consistent way.

引用完整性是确保以一致的方式保存相关数据的好方法。

#9


0  

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.

外键约束还阻止无效数据插入外键列,因为它必须是它指向的表中包含的值之一。

#10


-1  

First of all. Good Question !!

首先。好问题! !

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

MySql是RDBMS关系数据库管理系统,所以所有实体(表)都由一个列关联。

EMPLOYEE - EMPID EMPNAME DEPTID

员工- EMPID EMPNAME DEPTID。

DEPARTMENT - DEPTID DEPTNAME

部门——DEPTID DEPTNAME

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

DEPTID在EMPLOYEE表中是foriegn键,在DEPARTMENT表中是主键。

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.

为了检索数据,我们需要很少的语法和SQL创建者的描述。

SELECT * from EMPLOYEE

从员工选择*

SELECT * FROM DEPARTMENT

从部门选择*

SELECT * FROM EMPLOYEE WHERE DEPTID = 5

从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.

在这里,我们已经为我们的说服力重新分配了两个假想的表,但是对于所需的结果,我们使用了DEPTID = 5的语法。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/12/15/a825cdfb13518baf834b4810897b5b06.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com