mysql - 在另一个表中保留/分配一个新行,并将每一行添加到一个表中

标签 mysql sql database

我想知道是否可以执行以下操作:

  • 向表a插入数据后,表b中将自动创建一行,并且Note_Id(其主键)将存储在其中一个属性中(这是引用表中主键的外键) b) 表a中。
<小时/>
 CREATE TABLE table_a ( D_Id int(5) NOT NULL AUTO_INCREMENT,
 User_Id int(8) not null,
 Note_Id int(5) not null, -- this is the foreign key that points to table b 
 PRIMARY KEY (D_Id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 CREATE TABLE table_b ( Note_Id int(5) NOT NULL AUTO_INCREMENT,
 Note_Description varchar(50) null, 
 PRIMARY KEY (Note_Id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

谢谢!

 delimiter $$
 CREATE TRIGGER ins_Document
 AFTER INSERT ON TABLE_A FOR EACH ROW
 BEGIN
   set @notenum=(Select max(Note_Id) from TABLE_B);
   if(@notenum=0) then begin new.Note_Id=1;
   end;
   else
     new.Note_Id=@notenum+1;
   end if;
 INSERT INTO TABLE_B (Note_Id) VALUES (NEW.Note_Id); 
 END$$
 delimiter ;

最佳答案

查看触发器:Create Trigger 在这里,您可以对插入表等事件使用react,并为其定义相应的操作。

关于mysql - 在另一个表中保留/分配一个新行,并将每一行添加到一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22303227/

相关文章:

php - 生成唯一的 View ID

mysql - 根据匹配的列值插入值

PHP mysql 查询返回空白屏幕

java - Oracle Apex自定义登录页面身份验证

node.js - MongoDb 中的条件更新

php - Laravel 数据库严格模式

sql - 为什么我的查询这么慢?试图在 mysql 的左连接上找到空字段

java - 单击 ListView 中的项目时,Android 应用程序崩溃

MySQL IF 以数字开头做 X,否则做 Y

mysql - 按组计算 SQL 中的百分比