Mysql
 sql >> Database >  >> RDS >> Mysql

Riempi MySQL registra uno-a-molti tabelle correlate in un'unica azione

Dovresti usare due comandi INSERT; oppure prova a utilizzare un trigger INSERT.

MODIFICA:

--Un esempio con trigger:

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 |
+----+----------+---------+