MySQL 1:10固定关系。如何在数据库级实现它?

时间:2017-02-21 08:25:24

标签: mysql mysql-workbench

是否可以实现一个1:N关系,该关系最多包含many表中one引用1行的10行?

// ID int
INSERT INTO one VALUES (1);
// ...
INSERT INTO one VALUES (25);

//ID int, one_id int
INSERT INTO many VALUES (1,1);
// ...
INSERT INTO many VALUES (1,10);
INSERT INTO many VALUES (1,11); // ERROR!

INSERT INTO many VALUES (2,11); // working
// ...
INSERT INTO many VALUES (2,20); // working
INSERT INTO many VALUES (2,21); // ERROR!

1 个答案:

答案 0 :(得分:1)

您可以使用触发器执行此操作:

create trigger trg_mytable_max10 before insert on mytable
for each row
begin
  declare cnt int;
  set cnt = (select count(*) from mytable where col1 = new.col1);
  if cnt = 10 then
    signal sqlstate '45000' set message_text = 'only 10 records per col1 allowed';
  end if;
end;

http://rextester.com/EORH56497