MySQL - 连接新生成字段中的现有字段

时间:2018-02-24 07:13:58

标签: mysql database

在我的表格中,我有两个字段:bookreference。两者都不是必须独立的。但是,这两个值的连接值必须是唯一的。

我试图创建一个连接两者的生成列,但是我在运行SQL时收到以下错误消息:

Executing:
ALTER TABLE `bibleverses`.`myverses` 
ADD COLUMN `fullref` VARCHAR(20) GENERATED ALWAYS AS (CONCAT(book, reference)) STORED AFTER `mp3`;

    Operation failed: There was an error while applying the SQL script to the database.
    ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GENERATED ALWAYS AS (CONCAT(book, reference)) STORED AFTER `mp3`' at line 2
    SQL Statement:
    ALTER TABLE `bibleverses`.`myverses` 
    ADD COLUMN `fullref` VARCHAR(20) GENERATED ALWAYS AS (CONCAT(book, reference)) STORED AFTER `mp3`

Here is a screenshot of my current settings.

2 个答案:

答案 0 :(得分:1)

只需将UNIQUE键约束应用于这两列,就可以实现这一点,它将成为一个复合键,以便您可以将唯一值存储在这两列中。您可以尝试以下SQL语句:

ALTER TABLE bibleverses.myverses ADD UNIQUE(book, reference);

答案 1 :(得分:0)

首先执行alter table添加新列,然后运行更新以填充fild,如:

ALTER TABLE <table_name> ADD COLUMN <column name, type, definition, etc>;
UPDATE TABLE <table_name> SET <field> = <value>;