如果我有以下关系强制实施企业约束
Articles
articleId(PK)
title
content
date
而且说我的企业的约束是:
There may be only 10 articles in this table at anyone time
什么是执行上的MySQL这家企业约束的最佳方式数据库?它纯粹是由代码处理?我是否应该更改数据库中的任何内容来强制执行此类限制?
如果我有以下关系强制实施企业约束
Articles
articleId(PK)
title
content
date
而且说我的企业的约束是:
There may be only 10 articles in this table at anyone time
什么是执行上的MySQL这家企业约束的最佳方式数据库?它纯粹是由代码处理?我是否应该更改数据库中的任何内容来强制执行此类限制?
我会用一个触发器。
你可以做到这一点,像这样:
DELIMITER $$
CREATE TRIGGER bi_articles_each BEFORE INSERT ON articles FOR EACH ROW
BEGIN
DECLARE number_of_articles INTEGER;
SELECT count(*) INTO number_of_articles FROM articles;
IF number_of_articles > 10 THEN
//select from a non_existing query to force an error and prevent the insert
SELECT error
FROM `There may be only 10 articles in the article table at anyone time`;
END IF;
END $$
DELIMITER ;
参见:
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
http://www.databasedesign-resource.com/mysql-triggers.html
错误产生是一个有点笨重,但除此之外,它就像一个魅力。我用它所有的时间。
关于触发器的好处在于,无论您使用的插入向量如何,它都可以保证正常工作,并且它允许您保留(使用)用于插入,删除和更新的标准SQL,这非常方便。
我将创建用于插入将被专门用于插入新篇文章的存储过程。 在那里,我会检查你可能有的任何自定义约束。
如果一个自定义的约束被违反,那么你可以用信号被违反了什么约束(例如经由回归变量)的客户端,并插入文章跳过。