简体   繁体   English

MySQL是否在一个表上允许两个主键?

[英]Does MySQL allow two primary keys on one table?

CREATE TABLE Orders
-> (
->    ID SMALLINT UNSIGNED NOT NULL,
->    ModelID SMALLINT UNSIGNED NOT NULL,
->    Descrip VARCHAR(40),
->    PRIMARY KEY (ID, ModelID)
-> );

Basically, this appears to me to be creating two primary key on one table. 基本上,对我来说,这似乎是在一个表上创建两个主键。 Is that correct? 那是对的吗?

I thought that we could create a number of unique keys in one table, but only one primary key. 我以为我们可以在一个表中创建多个唯一键,但是只能创建一个主键。

How is it that my system is allowing the creation of multiple primary keys? 我的系统如何允许创建多个主键?

Please advise: what are the rules governing this? 请告知:关于此的规则是什么?

您的系统不允许使用多个主键-它基于2列(ID, ModelID)创建密钥

You are making 1 primary key. 您正在制作1个主键。 But that key is a combination of 2 values. 但是那个关键是两个值的组合。

Which is not a wrong thing to do. 这不是错的事。 But in your case it does look wrong. 但是在您的情况下,它看起来确实不对。

You seem to have a primary key named ID and a foreign key named ModelID . 您似乎有一个名为ID的主键和一个名为ModelID的外键。 You should probable have an index on the ModelID , and a primary key constraint on the ID 您应该在ModelID上有一个索引,并在ID上有一个主键约束

Think of it like it suggest, a 'KEY'. 像它建议的那样思考它,一个“关键”。 So the key would be all of the columns specified. 因此,键将是所有指定的列。 In your case you can have multiple rows with the same 'ID' and multiple rows with the same 'ModelID' but there shall never be two rows that have the same 'ID' AND 'ModelID'. 在您的情况下,可以有多个具有相同“ ID”的行和多个具有相同“ ModelID”的行,但决不能有两行具有相同的“ ID”和“ ModelID”。

So in this case it is not saying that the column 'ID' must be unique nor is it saying that 'ModelID' must be unique, but only the combination. 因此,在这种情况下,并不是说“ ID”列必须是唯一的,也不是说“ ModelID”必须是唯一的,而不仅仅是组合。

You can have one primary key (thats why it is called the primary key) 您可以有一个主键(这就是为什么它被称为键)

You can have multiple UNIQUE keys if you like. 如果愿意,可以有多个UNIQUE键。

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

相关问题 在一个表中拥有三个主键(其中两个是外键)是否有意义? - Does it make sense to have three primary keys, two of which are foreign keys, in one table? MySQL数据库在一个表中具有两个外键 - MySQL database with two foreign keys in one table 如何创建具有两个主键的表,其中一个是一个表中的外键,另一个是另一个表中的外键? - how to create a table with two primary keys where one is foreign key in one table and the other on another table? 使用两个外键作为主键 - MySQL - Using two foreign keys as a primary key - MySQL Java/Mysql 从一个表中选择主键值并将它们作为外键插入到另一个表中 - Java/Mysql Selecting Primary Key values from one table and Insert them to another table as Foreign Keys SQL 两个外键链接到另一个表的一个主键以从该表中提取字段 - SQL Two foreign keys linked to one primary key of another table to pull field from that table 如何使用两个外键作为一个主键将域表与第二个表连接起来? - How to join domain table with second table using two foreign keys for one primary key? 为什么不允许表中有两个主键? - Why two primary keys in a table is not allowed? 将两个外键链接到一个主键 - Linking Two Foreign Keys to one Primary Key 表格中的两个主非复合键 - Two primary non composite keys in a table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM