简体   繁体   English

如何使用默认约束为 mysql 中的列创建随机数?

[英]How to create random number for a column in mysql with DEFAULT Constraint?

The DEFAULT constraint has no problem in accepting string or current date values. DEFAULT 约束在接受字符串或当前日期值时没有问题。 What i need is an constraint that will create an random 4 digit number every time an entity is created.我需要的是一个约束,它会在每次创建实体时创建一个随机的 4 位数字。 I tried the following code but it returns an syntax error.我尝试了以下代码,但它返回语法错误。

ALTER TABLE client_number ADD(code INT(4) DEFAULT FLOOR(RAND()*9999)+1111); ALTER TABLE client_number ADD(代码 INT(4)默认楼层(RAND()* 9999)+ 1111);

The above statement returns following error:上面的语句返回以下错误:

#1064 - You have an error in your SQL syntax; #1064 - 您的 SQL 语法有误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'floor(rand()*9999)+1111)' at line 1查看与您的 MySQL 服务器版本对应的手册,了解在第 1 行的“floor(rand()*9999)+1111)”附近使用的正确语法

Need solution.需要解决方案。

This is too long for a comment. 这个评论太长了。

The documentation is quite clear: 文档很清楚:

The DEFAULT value clause in a data type specification indicates a default value for a column. 数据类型规范中的DEFAULT值子句指示列的默认值。 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. 您需要使用触发器。

Run the below query运行以下查询

ALTER TABLE table_name ADD field_name INT(4) NOT NULL DEFAULT (rand() * (9999 - 1000) + 1000) AFTER some_feild ; ALTER TABLE table_name ADD field_name INT(4) NOT NULL DEFAULT (rand() * (9999 - 1000) + 1000) AFTER some_feild ;

The result gives a random number between 1000-9999结果给出一个1000-9999之间的随机数在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM