简体   繁体   English

mysql中是否有机制可以基于任意值限制INSERT

[英]Are there mechanisms in mysql to limit INSERT based on arbitrary value

If I want to limit number of entries per user in this table: 如果要限制此表中每个用户的条目数:

CREATE TABLE `connections` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL,
  `word_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `No duplicates` (`user_id`,`word_id`),
  KEY `word_id` (`word_id`),
  CONSTRAINT `connections_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `connections_ibfk_2` FOREIGN KEY (`word_id`) REFERENCES `words_en` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

And this limit can change and I store it in another table called settings. 这个限制可以更改,我将其存储在另一个名为“设置”的表中。

Should I do first SELECT and than do php compare and than INSERT. 我应该先执行SELECT,然后再进行php比较和插入。 or is there a mechanism to do this kind of operations directly in INSERT query? 还是有一种机制可以直接在INSERT查询中执行这种操作?

DELIMITER $$
create
  trigger `some trigger` AFTER INSERT
  on table
  for each row begin
  if (select count(id) from someothertable)>=100 then
    delete from table  WHERE id = NEW.id -99;  
end$$
DELIMITER ;

I`m afraid I`m out of my depth,I think I could do it given enough time for research,but you`d better ask somebody more informed.Here is my half-assed trigger,not tested. 恐怕我无法深入研究,我想我可以给足够的时间进行研究,但是您最好问一个更了解的人。这是我半定的触发器,未经测试。

There is also Create Event in mysql you could use. 您也可以在mysql中使用Create Event。 http://www.sitepoint.com/how-to-create-mysql-events/ http://www.sitepoint.com/how-to-create-mysql-events/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM