如果我有以下关系
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 进行插入、删除和更新,这非常方便。
关于php - 对 MySql 数据库关系实现企业约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7230129/