简体   繁体   English

有没有办法在表中没有主键的情况下创建外键关系

[英]Is there any way to create foreign key relation without primary key in the table

I want to know, can a referential constraint be created between two tables, if the one is not having primary key. 我想知道,如果一个表没有主键,是否可以在两个表之间创建引用约束。

For example: 例如:

   Table1
   {
        Column1(Unique Key)

        Column2(Not Null)

        Column3(Candidate key)
    }

    Table2
    {
         Column1(Primary Key)

         Column2(Foreign Key)   //Can it refer to any of the column in Table1

         Column3
    }

Can it refer to any of the column in Table1 它可以引用表1中的任何列吗

If you want to create a foreign key to another column which is not Primary key, it must be unique. 如果要为不是主键的另一列创建外键,则它必须是唯一的。 (Unique Key on your column1) (列上的唯一键1)

But, what doesn't prevent you to do Column1 of Table1 as Primary key ?! 但是,什么不阻止您将Table1的Column1做为主键?! It's already an Unique Key and Table1 doesn't have a primary key... 它已经是唯一键,并且Table1没有主键...

Can it refer to any of the column in Table1 它可以引用表1中的任何列吗

I haven't tested it myself and I can't figure how it can work but, apparently, it can as long as you have an index ( any kind of index :-! ) where columns come first: 我还没有亲自测试过它,也无法弄清楚它是如何工作的,但是,显然,只要您有一个索引(列的任何一种:-! ),列就在第一位即可:

Foreign key definitions for InnoDB tables are subject to the following conditions: InnoDB表的外键定义必须满足以下条件:

  • InnoDB permits a foreign key to reference any index column or group of columns. InnoDB允许外键引用任何索引列或列组。 However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order. 但是,在引用表中,必须有一个索引,其中引用列以相同的顺序列为第一列

  • InnoDB does not currently support foreign keys for tables with user-defined partitioning. InnoDB当前不支持具有用户定义分区的表的外键。 This means that no user-partitioned InnoDB table may contain foreign key references or columns referenced by foreign keys. 这意味着没有用户划分的InnoDB表可以包含外键引用或外键引用的列。

  • InnoDB allows a foreign key constraint to reference a non-unique key . InnoDB允许外键约束引用非唯一键 This is an InnoDB extension to standard SQL. 这是对标准SQL的InnoDB扩展。

But even if the engine allows it, I wouldn't recommend to use a non-unique index (like Table1.Column2 in your example). 但是,即使引擎允许,我也不建议使用非唯一索引(如Table1.Column2中的Table1.Column2 )。

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

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