I am having trouble with this table
CREATE TABLE `Participants` (
`meetid` int(11) NOT NULL,
`pid` varchar(15) NOT NULL,
`status` char(1) DEFAULT NULL,
PRIMARY KEY (`meetid`,`pid`),
CONSTRAINT `participants_ibfk_1` FOREIGN KEY (`meetid`) REFERENCES `Meetings` (`meetid`) ON DELETE CASCADE
CONSTRAINT `participants_ibfk_2` CHECK (status IN ('a','d','u'))
CONSTRAINT `participants_ibfk_3` CHECK (pid IN (SELECT name FROM Rooms) OR pid IN (SELECT userid FROM People))
);
I want to have a foreign key constraint, and that works. Then i want to add a constraint to the attribute status
so it can only take the values 'a', 'd' and 'u'. It is not possible for me to set the field as Enum
or set
.
Can anyone tell me why this code does not work in MySQL?
CHECK
constraints are not supported by MySQL. You can define them, but they do nothing (as of MySQL 5.7).From the manual:
The workaround is to create triggers, but they aren't the easiest thing to work with.
If you want an open-source RDBMS that supports
CHECK
constraints, try PostgreSQL. It's actually a very good database.Beside triggers, for simple constraints like the one you have:
you could use a
Foreign Key
fromstatus
to a Reference table (ParticipantStatus
with 3 rows:'a','d','u'
):I don't understand why nobody here has mentioned that VIEW WITH CHECK OPTION can be a good alternative to the CHECK CONSTRAINT in MySQL:
There is a doc on the MySQL site: The View WITH CHECK OPTION Clause
P.S.: Keep in mind that your view should be updatable! See MySQL Updatable Views (thanks Romeo Sierra for clarification in comments).
Here is a way of getting the checks you wanted quickly and easily: