I have a table called modules and I want to enforce the following logic, but I am not sure the best way to do it. I was thinking adding an update and insert trigger, but having issues with the trigger code.
If the module_sub_id greater than ZERO, then check to see if the module_sub_id exists as a module_id. If ZERO then consider the row a parent record.
The idea that I am trying to do is have a parent record which can have children records, without having another table with a foreign key relationship between them.
CREATE TABLE `jlimited_test2`.`modules` (
`module_id` int( 11 ) NOT NULL AUTO_INCREMENT
, `module_sub_id` int( 11 ) NOT NULL default '0'
, `module_name` varchar( 100 ) CHARACTER SET utf8 NOT NULL
, `module_active` int( 11 ) NOT NULL
, PRIMARY KEY ( `module_id` )
) ENGINE = MYISAM DEFAULT CHARSET = latin1;
Here is the code for my trigger.
CREATE TRIGGER myTrigger
BEFORE INSERT ON modules
FOR EACH ROW
BEGIN
IF NEW.module_sub_id > 0 THEN
IF NOT (
SELECT count(*)
FROM modules
WHERE module_id = NEW.module_sub_id
) = 1 THEN
INSERT ignore()
END IF;
END IF;
END$$