实现mysql行约束的方法

时间:2011-12-09 14:20:58

标签: mysql datetime row constraints

有没有人知道它是否可以在MySQL中实现行约束?

假设我有一个非常简单的表来维护网上商店的促销代码:

CREATE TABLE `promotioncodes` (
  `promotionid` int(11) NOT NULL AUTO_INCREMENT,
  `promotioncode` varchar(30) DEFAULT NULL,
  `partnerid` int(11) DEFAULT NULL,
  `value` double DEFAULT NULL,
  `nr_of_usage` int(11) NOT NULL DEFAULT '0',
  `valid_from` datetime DEFAULT '0000-00-00 00:00:00',
  `valid_through` datetime DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`promotionid`),
  UNIQUE KEY `promotioncode_unique` (`promotioncode`)
)

有没有办法确保插入或更新行时

1)'valid_from'日期始终为'较小'(就日期而言),然后是'valid_through'。

2)如果'valid_from'碰巧留空/ null'valid_through'也必须为空/ null。

3)如果'valid_through'碰巧留空/ null'valid_from'也必须为空/ null。

我介绍了一些关于触发器和存储过程的东西,但我不觉得这些是解决方案:/?如果它们是解决方案,那么请给我一个具体的例子来说明如何实现这个

1 个答案:

答案 0 :(得分:1)

您应该创建将插入数据的存储过程。在此存储过程中,您可以实现所需的任何规则。

以下是示例。

create procedure promotioncodes_insert(
  IN...  list of params
  OUT error_code
)
exec:begin
  set error_code = 0; -- everything is ok

  if valid_from > valid_thru then
    set error_code = -1; -- error
    leave exec;
  end if;

  if (valid_from is null) and (valid_thru is not null) then
    set error_code = -2; -- another kind of error
    leave exec;
  end if;

  -- and so on

  -- doing insert

end;

请注意,如果您执行insert into promocodes() values()之类的直接插入,则这些限制将无效。