简体   繁体   English

像在SQL中一样插入GENERATED ALWAYS

[英]Insert GENERATED ALWAYS as in SQL

I created a table like this: 我创建了一个这样的表:

CREATE TABLE `group` (
  `g_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `owner_id` int(10) unsigned NOT NULL,
  `g_name` varchar(45) NOT NULL,
  `refer_code` varchar(45) GENERATED ALWAYS AS (concat(`g_name`)) VIRTUAL,
  `created_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `row_hash` varchar(256) NOT NULL,
  PRIMARY KEY (`g_id`),
  UNIQUE KEY `g_hash_UNIQUE` (`row_hash`),
  UNIQUE KEY `refer_UNIQUE` (`refer_code`),
  KEY `owner_idx` (`owner_id`),
  CONSTRAINT `owner_id` FOREIGN KEY (`owner_id`) REFERENCES `user` (`u_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The update statement gives me error: 更新语句给我错误:

INSERT INTO `server`.`group` (`owner_id`, `g_name`, `refer_code`, `created_on`, `row_hash`) 
VALUES ('4', 'cool', null, '2018-02-13 10:34:11', '452345324')

Error Code: 3105. The value specified for generated column 'refer_code' in table 'group' is not allowed. 错误代码:3105。不允许为表“组”中的已生成列“ refer_code”指定值。

How to specify the refer_code while inserting? 插入时如何指定refer_code

Values of the generated column are computed from the expression in the column definition of your CREATE TABLE , so don't include it in INSERT or UPDATE statements: 生成的列的值是根据CREATE TABLE的列定义中的表达式计算得出的,因此请勿将其包括在INSERTUPDATE语句中:

INSERT INTO `server`.`group` (`owner_id`, `g_name`, `created_on`, `row_hash`) 
VALUES ('4', 'cool', '2018-02-13 10:34:11', '452345324')

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

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