1

我一直认为需要表之间的关系来进行跨表操作,比如join。但我注意到我可以内部连接两个根本没有链接的表(没有任何外键)。

所以,我的问题:

  1. 连接链接表和非链接表是否存在一些差异(例如速度)?
  2. 使用关系表的优点/缺点是什么?

先感谢您。

4

3 回答 3

4

主要优点是外键约束确保数据的关系完整性。即它阻止您删除在另一个表中具有相关条目的内容

只有在 FK 上创建索引才能获得性能优势

于 2013-06-22T11:06:21.073 回答
2

The FK/PK relationship is a logical feature of the data that would exist even if it were not declared in a given database. You include FKs in a table precisely to establish these logical relationships and to make them visible in a way that makes useful inner joins possible. Declaring an FK as referencing a given PK has the advantage, as said in other answers, of preventing orphaned references, rows that reference a non existent PK.

Indexes can speed up joins. In a complicated query, the optimizer may have a lot of strategies to evaluate, and most of these will not use every available index. Good database systems have good optimizers. In most database systems, declaring a PK will create an index behind the scenes. Sometimes, but not always, creating an index on the FK with the same structure as the index n the PK will enable the optimizer to use a strategy called a merge-join. In certain circumstances a merge-join can be much faster than the alternatives.

When you join tables that are apprently unrelated, there are several cases.

One case is where you end up matching every row from table A with every row from table B. This is called a cartesian join. It takes a long time, and nearly always produces unintended results. One time in ten years I did an intentional cartesian join.

Another case is where both tables contain the same FK, and you match along those two FK. An example might be matching by ZIPCODE. Zipcodes are really FKs to some master zipcode table somewhere out there in post office land, even though most people who use zipcodes never realize that fact.

A third case is where there is a third table, a junction table, containing FKs that reference each of the two tables in question. This implements a many-to-many relationship. In this case, what you probably want to be doing is a three way join with two inner joins each of which has an FK/PK matchup as the join condition.

Either I'm telling a lot that you already know, or you would benefit by going through a basic tutorial on relational databases.

于 2013-06-22T11:40:30.087 回答
1

在关系数据库术语中,关系(或多或少)是您称为的数据结构- 它不是存在于“表之间”的东西。关系模型的一个重要优点是没有预定义的链接或其他导航结构来限制数据可以连接或以其他方式组合的方式。您可以随意在查询中加入关系(表)。

您要问的实际上称为外键约束。外键是一种约束,通过防止在数据库中填充不一致的值来帮助确保数据完整性。

于 2013-06-22T14:04:48.320 回答