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

[英]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