I’m trying to use MySQL to perform a check as a record is inserted into a table to see if a pair of values has already been used in another record.
The scenario is this:
I have a table called WORKLOG with the following columns:
LOGNO INTEGER UNSIGNED NOT NULL PRIMARY KEY,
HOURNO MEDIUMINT UNSIGNED NOT NULL,
EMPID INTEGER UNSIGNED NOT NULL,
JOBID INTEGER UNSIGNED NOT NULL,
DESCRIPTION TEXT,
the thing is that multiple records cannot have the same HOURNO and JOBID pair as it would mean the same hour of work is being done on the same job twice. Each job has it’s own track of hours so the hours can’t be unique on it’s own. I’m basically trying to implement a unique pair, kinda like a composite primary key.
so if I have the following rows in the table
(0001,1,0034,2938,"some text")
(0002,2,0034,2938,"some text")
(0003,1,0045,2939,"some text")
(0004,3,0034,2938,"some text")
(0005,2,0056,2939,"some text")
(0006,4,0034,2938,"some text")
(0007,3,0083,2939,"some text")
(0008,4,0083,2939,"some text")
I shouldn’t be able to add the following as the pair of HOURNO and JOBID already exist in another row (namely row 0006):
(0009,4,0056,2938,"some text")
is there a check I can do for this?
I’d recommend adding a UNIQUE constraint on those two columns. They sound like a composite candidate key. That way the database will enforce referential integrity for you. Make sure your tables are InnoDB.