gpt4 book ai didi

mysql - mysql行约束的实现方式

转载 作者:行者123 更新时间:2023-11-29 00:51:22 26 4
gpt4 key购买 nike

有谁知道是否可以在 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' 恰好留空/为空 'valid_through' 也必须为空/空。

3) 如果 'valid_through' 恰好留空/为空 'valid_from' 也必须为空/空。

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

最佳答案

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

这是例子。

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(),这些约束将不起作用。

关于mysql - mysql行约束的实现方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8446835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com