简体   繁体   中英

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. It has three lines which I cannot understand.

在此处输入图片说明

In test table's row 4 (line 6) "RelationTo" column's testCategoryList.CategoryId. Does it mean that test table's foreign key testCategory is the Primary key of testCategoryList table?

But, test table's foreign key testCategory is not the primary key of testCategoryList table. Other two rows (line 7 and line 8) have the same structure.

testCategoryList table:

在此处输入图片说明

testSubjectList table:

在此处输入图片说明

testLevelList table:

在此处输入图片说明 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.

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.

What your spreadsheet is clearly showing is that the FKs on the test table point to the PKs of the other three tables. For example the CREATE TABLE script for the test table would include:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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