views:

311

answers:

5

Hi Friends, 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.

+3  A: 

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

RC1140
+1  A: 
insert into sample_elements
     ( name, position, ownerel )
select 'Namespace1',
       sel.id,
       0
  from sample_elements sel
 where sel.name = "Namespace1";
Ian Kemp
+1  A: 

I think you can do it. You can use:

INSERT INTO table (..fields) SELECT ..fields.. FROM table;
mck89
A: 

I don't know mysql but can you try the following ?

insert into sample_elements select name, id, 0 from sample_elements where name='Namespace1'
Rahul
A: 

Am not sure , i thing this insert inside select for finding already exist or for what perpose ,

Thanks

Bharanikumar