Can I add a check constraint to a child checking t

2019-07-22 07:57发布

问题:

I have a similar database with two tables as follow:

+----------------------+           +------------------------+
|Persons               |           |phones                  |
+----------------------+           +------------------------+
|id       int          +-----+     |id          int         |
|name     varchar(100) |     +---->+person_id   int         |
|allowed  tinyint(1)   |           |number      int         |
+----------------------+           +------------------------+

One person could have as many phones as he wants but he has to be allowed to it (allowed > 0).

So, I created both tables using

CREATE TABLE `phones` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `persons_id` int(11) DEFAULT NULL,
  `phonenumber` int(5) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `phones_ibfk_1` (`persons_id`),
  CONSTRAINT `phones_ibfk_1` FOREIGN KEY (`persons_id`) REFERENCES `persons` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8` 

But this doesn't check what I want. What I want to know if it is possible make a query like ALTER TABLE phones ADD CONSTRAINT chk_person CHECK (persons.allowed > 0). Is this possible? There's another alternative?

回答1:

the check constraint doesn't work a solution is to create a trigger before insert so you check the values if you find something wron do an insert into the same table that will cause a erreur in

DELIMITER ||
CREATE TRIGGER  trigger_check  before insert ON phones  FOR EACH ROW 
begin 
DECLARE is_allowed boolean;
select allowed into @is_allowed from Persons where id = new.person_id;
if @is_allowed <1 then 
  insert into phones values ('','','','');  #make erreur doesn't metter
  end if ;
end ||
DELIMITER ;

that's how we do it for now hope that check constraint work in the new versions