[英]How to make the value of another column in a table to be the value of the primary key column in the same table?
I have a MySql Db_table called Branch with two fields ie "id" and "name".我有一个名为 Branch 的 MySql Db_table,其中包含两个字段,即“id”和“name”。 id is the primary key in this table.
id 是该表中的主键。 I want the value of the "name" column to be the value passed onto the "id" column.
我希望“name”列的值是传递到“id”列的值。 For example, I need something like this: if name == "cmc" then id should be equal to "cmc" etc.
例如,我需要这样的东西:if name == "cmc" then id should be equal to "cmc" etc.
id | name
CMC | CMC
How can I achieve this?我怎样才能做到这一点?
Update with the following logic:使用以下逻辑更新:
UPDATE yourTable
SET id = name
WHERE name = 'cmc';
If instead you want the name
column to always reflect the value of the id
, you may make name
a computed column:相反,如果您希望
name
列始终反映id
的值,则可以将name
设为计算列:
CREATE TABLE yourTable AS (
id varchar(100) NOT NULL PRIMARY KEY,
name varchar(100) AS (id),
...
)
Use AFTER INSERT trigger.使用 AFTER INSERT 触发器。
Something like this像这样的东西
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$$
Unfortunately I don't have MySql installed on my system to check exactly this code works, but you can check some examples here .不幸的是,我的系统上没有安装 MySql 来检查这段代码是否有效,但您可以在此处查看一些示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.