Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO with SubQuery MySQL

I have this Statement:

INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)     VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1)); 

I'm trying to insert a value copy the same data of item_costprice, but show me the error:

Error Code: 1136. Column count doesn't match value count at row 1 

How i can solve this?

like image 746
John Nuñez Avatar asked May 17 '12 22:05

John Nuñez


People also ask

Can we use subquery in insert?

Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date or number functions.

Can we use insert and SELECT together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

Can subqueries be used in inserts deletes and/or updates?

Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression operator.


2 Answers

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.

like image 132
Michael Berkowski Avatar answered Oct 12 '22 12:10

Michael Berkowski


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); 
like image 45
Elendurwen Avatar answered Oct 12 '22 10:10

Elendurwen