MySQL 如何在MySQL数据库中创建复合键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15302011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:49:16  来源:igfitidea点击:

how to create a composite key in MySQL database

mysqlcomposite-keycomposite-primary-key

提问by Ritabrata Gautam

i am working on mysql server.where i have created a table, named question . column/attributes of this table are (course,subject,year,question) i want to create a primary key(or composite key) consists of (course+subject+year). i.e. for a particular course+subject+year combination there can be only one question.there will be only one row with the combination of (course+subject+year),creation of another row won't be possible. i have done it by :

我在 mysql server.where 上工作,我创建了一个名为 question 的表。该表的列/属性是(课程、学科、年份、问题)我想创建一个由(课程+学科+年份)组成的主键(或复合键)。即对于特定的课程+学科+年份组合,只能有一个问题。只有一行是(课程+学科+年份)的组合,无法创建另一行。我已经做到了:

primary key(course,subject,year);

but it's not working.still i can create two rows with same combination of course,subject,year.

但它不起作用。我仍然可以用相同的课程、主题、年份组合创建两行。

can anyone tell me how can i create a composite key propery????

谁能告诉我如何创建复合键属性????

回答by Ritabrata Gautam

the syntax is CONSTRAINT constraint_name PRIMARY KEY(col1,col2,col3)for example ::

语法是CONSTRAINT constraint_name PRIMARY KEY(col1,col2,col3)例如 ::

CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

the above example will work if you are writting it while you are creating the table for example ::

如果您在创建表格时编写它,则上面的示例将起作用,例如 ::

CREATE TABLE person (
   P_Id int ,
   ............,
   ............,
   CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
);

to add this constraint to an existing table you need to follow the following syntax

将此约束添加到现有表中,您需要遵循以下语法

ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (P_Id,LastName)

回答by bizzehdee

if it is mysql you are looking at, you should do something similar to

如果您正在查看的是 mysql,则应该执行类似于

ALTER TABLE table_name ADD PRIMARY KEY (a, b, c);