如何让table中另一列的值成为同一个table中主键列的值?

How to make the value of another column in a table to be the value of the primary key column in the same table?

我有一个名为 Branch 的 MySql Db_table,它有两个字段,即“id”和“name”。 id 是这个 table 中的主键。我希望“name”列的值是传递到“id”列的值。例如,我需要这样的东西:if name == "cmc" then id should be equal to "cmc" etc.

 id  | name

 CMC | CMC

我怎样才能做到这一点?

更新逻辑如下:

UPDATE yourTable
SET id = name
WHERE name = 'cmc';

如果您希望 name 列始终反映 id 的值,您可以将 name 设为计算列:

CREATE TABLE yourTable AS (
    id varchar(100) NOT NULL PRIMARY KEY,
    name varchar(100) AS (id),
    ...
)

使用 AFTER INSERT 触发器。

像这样

CREATE TRIGGER after_your_table_insert
AFTER INSERT
ON your_table FOR EACH ROW
BEGIN
  IF NEW.name = 'CMC' THEN
    UPDATE your_table
    SET id = NEW.name;
  END IF;
END$$

很遗憾,我的系统上没有安装 MySql 来检查这段代码是否有效,但您可以查看一些示例 here