2

I have a fairly complicated database set up with lots of foreign key relationships and want to know if there is an easy way to insert an entry into one of these tables.

This is the table that holds some of the foreign keys.

CREATE TABLE package (
    id INT PRIMARY KEY AUTO_INCREMENT,
    master_id INT NOT NULL UNIQUE,
    library_id INT NOT NULL,
    FOREIGN KEY (master_id) REFERENCES master(id),
    FOREIGN KEY (library_id) REFERENCES library(id)
) DEFAULT CHARSET = utf8;

When this table is set up, it ends up only holding two foreign keys and Primary Key meaning everything in here is numbers. This is what I want to happen but that also means that an INSERT statement for this table would look like

INSERT INTO package (master_id, library_id) VALUES (235, 12);

or something like that...

Is there and way to make a statement like:

INSERT INTO package (master_id, library_id)
VALUES ([master_field], [library_field]);

where master_field and library_field are entries those tables? I'm not sure how this would be handled either because no other field in the master table is unique so what would happen if there were two entries...

Anyway if anyone knows how to do something like that it would be greatly appreciated! Doing all this inside MySQL is preferable but I have no problem with doing this using PHP.

1 Answer 1

2

You can do it all in MySQL by using a SELECT statement to provide the values for the INSERT. For example:

INSERT INTO package (master_id, library_id)
SELECT (SELECT master_field FROM master_table WHERE {some condition} LIMIT 1), (SELECT library_id FROM library_table WHERE {some condition} LIMIT 1)

You might want to not do it that way, though, and instead do separate SELECT statements in your PHP code so that you can deal errors more easily if, for example, there is no library_id that matches your condition.

1
  • Ok awesome, This looks like it will work well. I guess it would have to be done in PHP thought because of the problems with getting either more or less than 1 result... I was kinda hoping to stay outta PHP as much as possible but this will work great. Thank You! Mar 16, 2015 at 3:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.