sql >> Base de Datos >  >> RDS >> Mysql

Rellene los registros de MySQL de uno a muchos en tablas relacionadas en una sola acción

Debe usar dos comandos INSERT; o intente usar un activador INSERT.

EDITAR:

--Un ejemplo con activador:

CREATE TABLE dept(
  id INT(11) NOT NULL AUTO_INCREMENT,
  dept_name VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (id)
)
ENGINE = INNODB;

CREATE TABLE emp(
  id INT(11) NOT NULL AUTO_INCREMENT,
  emp_name VARCHAR(255) DEFAULT NULL,
  dept_id INT(11) DEFAULT NULL,
  PRIMARY KEY (id),
  CONSTRAINT FK_emp_dept_id FOREIGN KEY (dept_id)
  REFERENCES dept (id) ON DELETE RESTRICT ON UPDATE RESTRICT
)
ENGINE = INNODB;

DELIMITER $$

CREATE TRIGGER trigger1
AFTER INSERT
ON dept
FOR EACH ROW
BEGIN
  INSERT INTO emp VALUES (NULL, 'Someone', NEW.id);
END
$$

DELIMITER ;


-- Try to add new department.
INSERT INTO dept VALUES(NULL, 'Sales');

-- Is there new default employee?
SELECT * FROM emp;
+----+----------+---------+
| id | emp_name | dept_id |
+----+----------+---------+
|  1 | Someone  |       1 |
+----+----------+---------+