INSERT INTO with SubQuery MySQL
I was disappointed at the "all or nothing" answers. I needed (again) to INSERT
some data and SELECT
an id
from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
The sub-select on an INSERT
query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT
within an INSERT
I recommend testing your SELECT
independently first and ensuring that the correct number of columns match for both queries.
You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
((SELECT id FROM modules WHERE title="Top bar"),0,-100);
Use numeric literals with aliases inside a SELECT
statement. No ()
are necessary around the SELECT
component.
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
SELECT
/* Literal number values with column aliases */
1 AS item_code,
2 AS invoice_code,
item_costprice
FROM qa_items
WHERE item_code = 1;
Note that in context of an INSERT INTO...SELECT
, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice
, but in a normal SELECT
you'll need the aliases to access the columns returned.