Search code examples
mysqlworkbench

How to insert values into two tables with a foreign key relationship on mySql


npas

+-----+------+---------------------------+
| id  | npa  | town                      |
+-----+------+---------------------------+
|   1 |  104 |  Villars-le-terroir       |
+-----+------+---------------------------+

customers

+----+----------+-----------+------------------------+---------------+---------------------------+---------------+--------+
| id | lastname | firstname | address                | phone         | email                     | mobile        | npa_id |
+----+----------+-----------+------------------------+---------------+---------------------------+---------------+--------+
|  1 | Gentizon | Alain     | Derrière le Chateaux 6 | 021 000 00 00 | [email protected] | 077 000 00 00 |     96 |
+----+----------+-----------+------------------------+---------------+---------------------------+---------------+--------+


INSERT INTO customers (lastname,firstname,address,email,mobile) 
VALUES ('xycyxc', 'xcyc', 'xycyxc', 'xycyxcy', 'xycyxc');


INSERT INTO npas (npa,town) 
VALUES ('xycyxcy', 'xycyxc')

What should I do?

I am so sorry if my question is duplicate with other. I am fresher in SQL. Thanks for any help


Solution

  • INSERT INTO npas (npa, town) 
        VALUES ('npa', 'town');
    
    INSERT INTO customers (lastname, firstname, address, email, mobile, npa_id) 
        SELECT 'lastname', 'firstname', 'address', 'email', 'mobile', npas.id
        FROM npas
        WHERE npas.npa = 'npa' AND npas.town = 'town';