Can I add a check constraint to a child checking the value of its parent in MySQL?

百般思念 提交于 2019-12-11 05:16:22

问题


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



来源:https://stackoverflow.com/questions/38399718/can-i-add-a-check-constraint-to-a-child-checking-the-value-of-its-parent-in-mysq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!