1

Let’s consider table

Video(
    IDvideo(PK),
    Date,
    Description,
    User
)

with mysql I have no way of writing assertions. Is it possible to simulate the following assertion using one or more triggers ?

create assertion asser1  
check (0 = 
    ( select count(*)  
      from Video  
      where Date >= DATE_SUB(current_date(),INTERVAL  1 YEAR ) 
          && Date<=current_date()  
      group by User   
      having count(*) > 200
    )
)

how should I write that trigger?

4

1 回答 1

1

好吧,问题是 MySQL 没有等效的STOP ACTION命令。所以基本上,解决方法很脏:

一种方法是您可以违反触发器内部的约束来冒泡错误并取消插入:

CREATE TABLE stop_action (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(35),
    UNIQUE KEY (id, name)
);
INSERT INTO stop_action (1, 'Assert Failure');

然后,在触发器中,尝试:

INSERT INTO stop_action (1, 'Assert Failure');

这样做的好处是,返回的错误将是重复键错误,并且文本将包括“断言失败”。

那么你的触发器将变为:

delimiter |

CREATE TRIGGER asser1_before BEFORE INSERT ON test1
  FOR EACH ROW BEGIN
    SELECT count(*) INTO test FROM (select count(*)
          from Video  
          where Date >= DATE_SUB(current_date(),INTERVAL  1 YEAR ) 
            && Date<=current_date()  
          group by User   
          having count(*) > 200);
    IF test != 0 THEN
        INSERT INTO stop_action (1, 'Assert Failure');
    END IF;
  END;
|

delimiter ;

现在,您之前也需要这样做UPDATE,否则您可能会将日期更新为无效状态。但除此之外,这至少应该让你开始......

于 2011-02-01T19:31:59.380 回答