Php mysql中是否有选项将一列设置为不大于另一列
mysql中是否有选项将一列设置为不大于另一列 在这种情况下,两列都是整型。我假定您的意思是:对于每一行,一列值不应大于另一列值 从MySQL 8.0.16开始,这可以通过检查约束实现:Php mysql中是否有选项将一列设置为不大于另一列,php,mysql,laravel,Php,Mysql,Laravel,mysql中是否有选项将一列设置为不大于另一列 在这种情况下,两列都是整型。我假定您的意思是:对于每一行,一列值不应大于另一列值 从MySQL 8.0.16开始,这可以通过检查约束实现: create table mytable ( id int, big_col int, small_col int, check (small_col <= big_col) ) 在MySQL的早期版本中,典型的解决方案是使用触发器进行插入和更新: delimiter /
create table mytable (
id int,
big_col int,
small_col int,
check (small_col <= big_col)
)
在MySQL的早期版本中,典型的解决方案是使用触发器进行插入和更新:
delimiter //
create trigger mytrigger_insert
before insert on mytable for each row
begin
if new.big_col < new.small_col then
signal sqlstate '45000'
set message_text = 'small_col must not be bigger than big_col';
end if;
end
//
delimiter ;
delimiter //
create trigger mytrigger_update
before update on mytable for each row
begin
if new.big_col < new.small_col then
signal sqlstate '45000'
set message_text = 'small_col must not be bigger than big_col';
end if;
end
//
delimiter ;
使用IFexp1、exp2、exp3设置编号,exp2可以更改为您想要的值
这将更新列1,但不超过列2
更新表
设置column1=IF100>column2,column2,100
哪里
拉维查询
\DB::selectupdate表
设置column1=IF:num1>column2,column2,:num2
其中…,[num1=>100,num2=>100]
希望这可以帮助您或其他人。尝试指定检查约束。如果可以的话,也可以尝试添加插入/更新触发器。请参阅,这样我们就可以更好地了解您正在谈论或试图获取的内容..不,更正检查是MySQL 8.0.16+,仅请参阅。。我已经够接近了:-在MySQL的早期版本中,一个典型的解决方案是使用触发器进行插入和更新:要在支持触发器的最旧MySQL版本中添加答案,您需要使用诸如更新“small\u col不得大于big\u col”之类的变通方法来触发良好的信号,因为通常不支持任何可能导致语法错误的内容可以/应该像a一样工作以获得可读性好的错误消息。@RaymondNijland:我认为signal语句从5.5版开始就存在了。。。您对最旧版本的评论与5.5版本之前的版本相关?您对最旧版本的评论与5.5版本之前的版本相关?是的,这就是我的意思,实际上SIGNAL是一个MySQL 5.5+语句,旧的MySQL 5.5之前版本没有SIGNAL语句。。还记得以前的MySQL网站/手动设计吗?无论如何,我想我会删除我的评论,因为人们现在不太可能仍然运行MySQL 5.0到MySQL 5.4…Laravel code\DB::rawIF$int>column2,column2,$int部分感觉非常容易SQL注入。。不确定有一段时间没有做Laravel编程,而且如果像updatefunction那样使用它可能会很好@RaymondNijland很抱歉。我已经更新了我的答案。
delimiter //
create trigger mytrigger_insert
before insert on mytable for each row
begin
if new.big_col < new.small_col then
signal sqlstate '45000'
set message_text = 'small_col must not be bigger than big_col';
end if;
end
//
delimiter ;
delimiter //
create trigger mytrigger_update
before update on mytable for each row
begin
if new.big_col < new.small_col then
signal sqlstate '45000'
set message_text = 'small_col must not be bigger than big_col';
end if;
end
//
delimiter ;
insert into mytable(id, big_col, small_col) values(1, 1, 0);
-- ok
insert into mytable(id, big_col, small_col) values(2, 1, 2);
-- error: ER_SIGNAL_EXCEPTION: small_col must not be bigger than big_col
update mytable set small_col = 2 where id = 1;
-- error: ER_SIGNAL_EXCEPTION: small_col must not be bigger than big_col