触发以将 N 个默认值插入行

Trigger to Insert N number of default values into row

所以我创建了以下触发器:

CREATE TRIGGER cascadeUserInsertionToRecommendations_tbl
    -> AFTER INSERT
    -> ON users_tbl FOR EACH ROW
    -> INSERT INTO recommendations_tbl(recommendation_userid, recommendation_category, recommendation_manufacturer) VALUES(NEW.user_id, 'diverse', 'diverse');
Query OK, 0 rows affected (0.027 sec)

实际上,我可以在其他字段上使用 Default() 而不是 "diverse",因为 "diverse" 实际上是这些列的默认值。但这不是这里的问题。

万一我扩展这个table,如果上面的触发器动态适应新情况,我将不胜感激。 基本上,触发器只需要用默认值填充新行的所有字段,接收 NEW.user_id 的字段除外。

我想知道 MySQL 是否提供了一些语法来完成此操作?

Basically, the Trigger just needs to fill ALL the fields of the new row with the default value except for the one receiving the NEW.user_id.

假设您为 recommendation_userid 除外的每个列正确定义了默认值,您所要做的就是在插入时不传递这些额外的列。 MySQL 将自动为您在插入时未提供的列分配默认值。

因此您的 INSERT 命令应该如下所示:

insert into recommendations_tbl(recommendation_userid) values(EW.user_id);

即使在目标 table 中创建了新列,这也将继续起作用(再次假设这些新列具有正确定义的默认值)。

Demo on DB Fiddle:

-- create the table with default values for all columns excepted the primary key
create table recommendations_tbl (
    recommendation_userid integer primary key, 
    recommendation_category varchar(10) default 'diverse',
    recommendation_manufacturer varchar(10) default 'diverse'
);


-- insert a record, providing the primary key only
insert into recommendations_tbl(recommendation_userid) values(1);

-- other columns were assigned default values
select * from recommendations_tbl;

recommendation_userid | recommendation_category | recommendation_manufacturer
--------------------: | :---------------------- | :--------------------------
                    1 | diverse                 | diverse