Question

I have 6 tables with ~2-15 attributes each, each one of these 6 tables has an ID which is constrained from another table. This 7th table has its own ID and the 6 other table ID's, as well as a date and comment attribute. This is the first 3NF database I have made, with this many attributes and I am confused on how when I add data to the first 6 tables, the id's will be inserted into the 7th.

enter image description here

Sorry for cutting out the table attribute names, its not top secret or anything i'd just rather not put the information online.

As for what exactly I need to do, is create a record relating each of those tables to a single table.

Was it helpful?

Solution

Generally you must insert the records into "slave" tables and then insert records into "main" table selecting slave IDs by the values just inserted:

INSERT INTO slave1 (field1_1, ...) 
    VALUES (value1_1, ...);

INSERT INTO slave2 (field2_1, ...) 
    VALUES (value2_1, ...);

...

INSERT INTO main (slave1_id, slave2_id, ...)
    VALUES ( (SELECT id FROM slave1 WHERE field1_1 = value1_1 AND ...),
             (SELECT id FROM slave2 WHERE field2_1 = value2_1 AND ...),
             ...
           );

In some cases (when you can guarantee that all queries will be executed in the same connection or your connector allows multi-queries, and all slave IDs are auto-increments) you can obtain LAST_INSERT_ID() for each slave table and use it while inserting into main table.

INSERT INTO slave1 (field1_1, ...) 
    VALUES (value1_1, ...);

SET @id1 := LAST_INSERT_ID();

INSERT INTO slave2 (field2_1, ...) 
    VALUES (value2_1, ...);

SET @id2 := LAST_INSERT_ID();

...

INSERT INTO main (slave1_id, slave2_id, ...)
    VALUES ( @id1, @id2, ... );

And the best solution (I think) is to use a stored procedure which accepts all parameters for all tables and performs all actions you need.

Of course, you must consider that any of inserts can fail by any reason, and take all actions to avoid inconsistent data. Transaction can help, for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top