Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT with SELECT

I have a query that inserts using a SELECT statement:

INSERT INTO courses (name, location, gid)  SELECT name, location, gid  FROM courses  WHERE cid = $cid 

Is it possible to only select "name, location" for the insert, and set gid to something else in the query?

like image 265
Kyle Avatar asked Mar 22 '11 12:03

Kyle


People also ask

Can insert be used with select?

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 I use select in insert statement SQL?

The SQL INSERT INTO SELECT StatementThe INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

How do I insert a select query result into a table?

From the Query Designer menu, point to Change Type, and then click Insert Results. In the Choose Target Table for Insert Results Dialog Box, select the table to copy rows to (the destination table).

Can a select block an insert?

Answering your question - yes, you can block any insert during read and this is called "Pessimistic Concurrency".


2 Answers

Yes, absolutely, but check your syntax.

INSERT INTO courses (name, location, gid) SELECT name, location, 1 FROM   courses WHERE  cid = 2 

You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.

like image 148
Andrew Avatar answered Oct 17 '22 17:10

Andrew


Yes, it is. You can write :

INSERT INTO courses (name, location, gid)  SELECT name, location, 'whatever you want'  FROM courses  WHERE cid = $ci 

or you can get values from another join of the select ...

like image 21
Dumitrescu Bogdan Avatar answered Oct 17 '22 16:10

Dumitrescu Bogdan