can we have a foreign key which is not a primary key in any other table?

前端 未结 4 674
春和景丽
春和景丽 2020-12-02 20:29

it is written in every book that foreign keys are actually primary key in some other table but can we have a foreign key which is not primary key in any other table

相关标签:
4条回答
  • 2020-12-02 20:56

    Yes - you can have a foreign key that references a unique index in another table.

    CREATE UNIQUE INDEX UX01_YourTable ON dbo.YourTable(SomeUniqueColumn)
    
    ALTER TABLE dbo.YourChildTable
       ADD CONSTRAINT FK_ChildTable_Table
       FOREIGN KEY(YourFKColumn) REFERENCES dbo.YourTable(SomeUniqueColumn)
    
    0 讨论(0)
  • 2020-12-02 21:00

    General standard answer is no. It is only possible if foreign key refers any column uniquely in other table. That means foreign key must be the candidate key in other table and primary key is also a candidate key the table.

    0 讨论(0)
  • 2020-12-02 21:01

    By definition a foreign key must reference a candidate key of some table. It doesn't necessarily have to be the primary key.

    As a matter of detail the constraint called a FOREIGN KEY in SQL isn't exactly equivalent to the textbook definition of a foreign key in the relational model. SQL's FOREIGN KEY constraint differs because:

    • it can reference any set of columns subject to a uniqueness constraint even if they are not candidate keys (superkeys or nullable columns for example).
    • it may include nulls, in which case the constraint is not enforced
    • its syntax depends on column order, so a fk constraint on (A,B) referencing (A,B) is different to a constraint on (B,A) referencing (A,B).
    0 讨论(0)
  • 2020-12-02 21:11

    Yes , There can be a foreign key which is unique key in other table as Unique key is subset of primary key but not the exact primary key.

    So that's possible that foreign key is unique key in aother table.

    0 讨论(0)
提交回复
热议问题