如何使用默认约束为 mysql 中的列创建随机数? [英] How to create random number for a column in mysql with DEFAULT Constraint?
问题描述
DEFAULT 约束在接受字符串或当前日期值方面没有问题.我需要的是一个约束,每次创建实体时都会创建一个随机的 4 位数字.我尝试了以下代码,但它返回一个语法错误.
The DEFAULT constraint has no problem in accepting string or current date values. What i need is an constraint that will create an random 4 digit number every time an entity is created. I tried the following code but it returns an syntax error.
ALTER TABLE client_number ADD(code INT(4) DEFAULT FLOOR(RAND()*9999)+1111);
以上语句返回以下错误:
The above statement returns following error:
#1064 - 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在第 1 行的floor(rand()*9999)+1111)"附近使用的正确语法
需要解决方案.
推荐答案
评论太长了.
文档 非常清楚:
数据类型规范中的 DEFAULT 值子句表示列的默认值.除了一个例外,默认值必须是一个常数;它不能是函数或表达式.
The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.
你的表达式不是常量,所以它不起作用.您需要改用触发器.
The expression you have is not a constant, so it doesn't work. You would need to use a trigger instead.
这篇关于如何使用默认约束为 mysql 中的列创建随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!