如何在MySQL中将多个字段设置为主键?


23

我有一张桌子

员工ID

等等

blahblah2

.....

记录月

回顾年

  • 因此,每个员工只应有一个匹配的条目来输入月,年,Emp#。如何设置表格。

那么,如何设置表以使EmployeeID可以每月更新一次,但永远不能在匹配的月份和年份中有两个条目?

Answers:


43

使用复合主键

CREATE TABLE yourtable 
  ( 
     employeeid  INT, 
     blahblah    VARCHAR(255), 
     blahblah2   VARCHAR(255), 
     recordmonth DATE, 
     recodrdyear DATE, 
     PRIMARY KEY (employeeid, recordmonth, recodrdyear) 
  ) 

如果表已经存在,则删除旧的主键:

ALTER TABLE yourtable
DROP PRIMARY KEY;

并重新创建它:

ALTER TABLE yourtable
ADD PRIMARY KEY (employeeid, recordmonth, recodrdyear);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.