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

时间:2019-01-29 02:25:45

标签: mysql sql

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));

不起作用,因为我试图将tag设为计算列

我想要两个表,user看起来像

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

kit看起来

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

应该从创建者的用户名和套件名称自动计算标签列。

我认为我的列声明会起作用:

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

但我想不是。

1 个答案:

答案 0 :(得分:0)

这样的事情(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 ;
相关问题