Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use select query inside the Insert query for the same table name

Tags:

mysql

Is it possible to use a "select" query inside the "Insert" query, But the condition is i want to use the same table name for both "select" and "Insert" query.
For Example
mysql> insert into sample_elements (name,position,ownerel) values ('Namespace1', select id from sample_elements where name='Namespace1',0);

Please guide me on this.

like image 964
praveenjayapal Avatar asked Oct 14 '09 07:10

praveenjayapal


People also ask

How do you select and insert in the same table?

The 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.

Can we use select statement in insert statement?

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.

Is it possible to use the same table twice in a select query?

You use a single table twice in a query by giving it two names, like that. The aliases are often introduced with the keyword AS. You also normally specify a join condition (for without it, you get the Cartesian Product of the table joined with itself). For preference you use the explicit JOIN notation.


2 Answers

Change your insert to look like the following :

insert into sample_elements (name,position,ownerel) select 'Namespace1',id,0 from sample_elements where name='Namespace1';

Basically instead of using values only use the select statement and insert the harcoded values as columns

like image 174
RC1140 Avatar answered Oct 14 '22 22:10

RC1140


I think you can do it. You can use:

INSERT INTO table (..fields) SELECT ..fields.. FROM table;
like image 27
mck89 Avatar answered Oct 14 '22 21:10

mck89