简体   繁体   English

如何在与外键和主键没有相同字段的两个表之间创建关系

[英]How to create relationship between two tables which have no same field as foreign key and primary key

I received an excel sheet from a client. 我从客户那里收到一张Excel工作表。 It has three lines which I cannot understand. 它有三行我无法理解。

在此处输入图片说明

In test table's row 4 (line 6) "RelationTo" column's testCategoryList.CategoryId. 在测试表的第4行(第6行)中,“ RelationTo”列的testCategoryList.CategoryId。 Does it mean that test table's foreign key testCategory is the Primary key of testCategoryList table? 这是否意味着测试表的外键testCategory是testCategoryList表的主键?

But, test table's foreign key testCategory is not the primary key of testCategoryList table. 但是,测试表的外键testCategory不是testCategoryList表的主键。 Other two rows (line 7 and line 8) have the same structure. 其他两行(第7行和第8行)具有相同的结构。

testCategoryList table: testCategoryList表:

在此处输入图片说明

testSubjectList table: testSubjectList表:

在此处输入图片说明

testLevelList table: testLevelList表:

在此处输入图片说明 Am I missing something? 我想念什么吗? Those three lines don't make any sense. 这三行没有任何意义。

I think your confusion might be over naming conventions. 我认为您可能对命名约定感到困惑。

Are you assuming that a foreign key column name must be identical to a primary key column name in order to match them? 您是否假设外键列名必须与主键列名相同才能匹配它们? This is absolutely not true. 绝对不是这样。 There was a time in pre-relational database days where some storage technologies did have this requirement, but it is not part of the SQL standard at all. 在关系前数据库时代曾经有一段时间,某些存储技术确实有此要求,但它根本不是SQL标准的一部分。

Nevertheless, there is a naming convention which is popular with many people in which foreign key names match primary key names exactly. 但是,有一种命名约定在许多人中很流行,其中外键名与主键名完全匹配。 This enables something called natural joins . 这将启用所谓的自然联接

However, not everyone agrees that this naming convention is a good idea. 但是,并非所有人都同意此命名约定是一个好主意。 A couple of problems with it are that (a) if you have two FK's from one table to another, you have to let go of the convention to avoid duplicate column names, and (b) you end up having to put the table name in front of every single column to avoid unintended natural joins, such as person.name against company.name. 它有两个问题:(a)如果从一个表到另一个表有两个FK,则必须放弃约定以避免重复的列名,并且(b)最后不得不将表名放在避免出现意外的自然联接,例如person.name与company.name的对应关系。

What your spreadsheet is clearly showing is that the FKs on the test table point to the PKs of the other three tables. 电子表格清楚显示的是, test表上的FK指向其他三个表的PK。 For example the CREATE TABLE script for the test table would include: 例如, test表的CREATE TABLE脚本将包括:

...
CONSTRAINT FK_TEST__TESTCATEGORYLIST FOREIGN KEY
    IX_TEST__TESTCATEGORY (testCategory)
    REFERENCES testCategoryList (categoryId)
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM