Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 对MySql数据库关系实施企业约束_Php_Mysql_Sql_Database_Constraints - Fatal编程技术网

Php 对MySql数据库关系实施企业约束

Php 对MySql数据库关系实施企业约束,php,mysql,sql,database,constraints,Php,Mysql,Sql,Database,Constraints,如果我有以下关系 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 BE

如果我有以下关系

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 ;
请参阅:

错误生成有点笨拙,但在其他方面,它就像一个魅力。我一直在用它


触发器的好处是,无论使用何种插入向量,它都能保证工作,并且允许您保留(使用)用于插入、删除和更新的标准SQL,这非常方便

我将创建一个用于插入新文章的存储过程,该过程将专门用于插入文章。 在那里,我将检查您可能具有的任何自定义约束

如果违反了自定义约束,则可以向客户端发出违反了什么约束的信号(例如,通过返回变量),并跳过插入文章