Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL INSERT INTO ... VALUES and SELECT

Is there a way to insert pre-set values and values I get from a select-query? For example:

INSERT INTO table1 VALUES ("A string", 5, [int]). 

I have the value of "A string" and the number 5, but I've to find the [int] value from a select like this:

SELECT idTable2 FROM table2 WHERE ... 

that gives me that id to put inside table1.

How to merge this into one statement?

like image 795
TheEnigmist Avatar asked Mar 20 '13 12:03

TheEnigmist


People also ask

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.

Which is faster insert into or select into?

INTO' creates the destination table, it exclusively owns that table and is quicker compared to the 'INSERT … SELECT'. Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage.

What is the difference between insert into and select into?

INSERT INTO SELECT vs SELECT INTO: Both the statements could be used to copy data from one table to another. But INSERT INTO SELECT could be used only if the target table exists whereas SELECT INTO statement could be used even if the target table doesn't exist as it creates the target table if it doesn't exist.


2 Answers

Use an insert ... select query, and put the known values in the select:

insert into table1 select 'A string', 5, idTable2 from table2 where ... 
like image 76
Guffa Avatar answered Sep 29 '22 07:09

Guffa


just use a subquery right there like:

INSERT INTO table1 VALUES ("A string", 5, (SELECT ...)). 
like image 36
Joey.Z Avatar answered Sep 29 '22 09:09

Joey.Z