mysql - 像在 SQL 中一样插入 GENERATED ALWAYS

标签 mysql sql

我创建了一个这样的表:

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;

更新语句给我错误:

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.

插入时如何指定refer_code

最佳答案

生成列的值是根据 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')

关于mysql - 像在 SQL 中一样插入 GENERATED ALWAYS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48830317/

相关文章:

sql - 是否可以动态提供 sp_ExecuteSql 参数名称?

MySQL 错误 : Cannot add foreign key constraint?

php - 如果不存在则插入到 MYSQL 数据库中

mysql - ORDER BY ... ASC 很慢, "Using index condition"

sql - oracle sql - 查询以查找特殊字符

sql - SQL Server中的可选参数

sql - 更新sql中的查询

mysql - Laravel 中数据库表的默认内容

php - 列表更新 - 行冲突

mysql - 如何在保护隐私的同时将 Fusion Tables 与 Google Maps API 结合使用?