33

I have a table with fields

EmployeeID

blahblah

blahblah2

.....

RecordMonth

RecordYear

  • so each employee should only have a matching entry for a month, year, Emp#. How do I set up a table.

So how do I set up the table so that EmployeeID can be updated once a month but can never have two entries for a matching month and year?

0

1 Answer 1

60

Use a compound primary key:

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

And if your table already exists, drop the old primary key:

ALTER TABLE yourtable
DROP PRIMARY KEY;

And recreate it:

ALTER TABLE yourtable
ADD PRIMARY KEY (employeeid, recordmonth, recordyear);
4
  • Hi, my db does not let me drop the primary key with the error 'Incorrect table definition; there can be only one auto column and it must be defined as a key') Commented May 30, 2020 at 7:07
  • 2
    so one should ALTER TABLE yourtable MODIFY id INT NOT NULL; first. Commented May 30, 2020 at 7:12
  • @DmitriyGrankin Yes. It's work for me Commented Oct 18, 2022 at 9:39
  • Will still be able to select based on either one of the three columns still? Commented Dec 4, 2022 at 22:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.