简体   繁体   中英

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.

How to specify the refer_code while inserting?

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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