简体   繁体   English

使用来自另一个表的值的计算列

[英]computed column using value from another table

create table kit(id int unsigned not null auto_increment, creator int unsigned not null, name varchar(16) not null, script longtext not null, tag as concat(select username from user where id = creator, '/', name), primary key (id));

doesn't work because I am trying to make tag a computed column 不起作用,因为我正在尝试使tag成为计算列

I want two tables, user looks like 我想要两个表, user看起来像

+----+------------------+
| id | username         |
+----+------------------+
|  1 | 1234567890123456 |
+----+------------------+

and kit looks like kit看起来像

+----+---------+--------+--------+-------------------------+
| id | creator |  name  | script |           tag           |
+----+---------+--------+--------+-------------------------+
|  1 |       1 | kitkit | long   | 1234567890123456/kitkit |
+----+---------+--------+--------+-------------------------+

The tag column should be auto-computed from the username of the creator and the name of the kit. 标签列应根据创建者的用户名和套件名称自动计算。

I thought my column declaration would work: 我以为我的列声明会起作用:

tag as concat(select username from user where id = creator, '/', name)

but I guess not. 但我想不是。

Something like this (NB! not tested) 像这样的东西(NB!未经测试)

create table kit(
id int unsigned not null auto_increment, 
creator int unsigned not null, 
name varchar(16) not null, 
script longtext not null, 
tag varchar(33) not null, primary key (id));

DELIMITER //
CREATE TRIGGER contacts_before_insert
BEFORE INSERT
   ON contacts FOR EACH ROW
BEGIN
   DECLARE vtag varchar(33);
   -- Fill tag value
   select concat(username,'/',OLD.name) from user where id = OLD.creator INTO vtag;

   -- Update created_by field to the username of the person performing the INSERT
   SET NEW.tag = vtag;

END; //

DELIMITER ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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