如何将数据插入具有外键的表中?

时间:2018-09-20 09:07:30

标签: mysql sql

我有2张桌子:

                 usine 
======================================
id_usine | nom_usine | referance_usine 

,对于每个usine,我们都有ligneproduction,所以我还有另一个表:

  ligneproduction
=================== 
id | nom | fkUsine 

我使用以下方法在表格中添加了一个项目:

INSERT INTO `USINE` (`id_usine`, `nom_usine`, `referance_usine`)
             VALUES ('3', 'LAFARGE BISKRA', 'LAFARGE_BISKRA');

我想在ligneproduction表中添加与usine表中该项目相对应的“ ligne production”。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用此...设置最后插入的ID并插入子表中,并使ligneproduction的ID自动递增

INSERT INTO `USINE` (`id_usine`, `nom_usine`, `referance_usine`)
                 VALUES ('3', 'LAFARGE BISKRA', 'LAFARGE_BISKRA');

    SET @id_usine = (SELECT LAST_INSERT_ID());

    INSERT INTO `ligneproduction` (`nom`, `fkUsine`)
                 VALUES ('any value depends on u', @id_usine);