tags:

views:

48

answers:

3
+3  Q: 

MySQL INSERT Query

Hi,

I need a query to perform the following: find the countryID where country = 'UK' from table Countries

then use the found value in

INSERT into towns (id, country_fk, name)
values (1, <value_found>, 'London').

is this possible?

UPDATE I need to store the value once so that I can use it in multiple INSERTS (about 100)

+1  A: 

You can use subquery there:

INSERT into towns (id, country_fk, name)
values (1, (SELECT countryID from countries where country = 'UK'), 'London')
zerkms
thanks zerkms, but I need to store the value once so that I can use it in multiple INSERTS (about 100)
mouthpiec
`You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where country = 'UK'), 'London')'`
Mark Byers
@Mark: the answer was missing the 'from' clause - are you getting any errors now?
stereofrog
No errors - it works now.
Mark Byers
+5  A: 

Yes it is possible. One option is to use the INSERT ... SELECT syntax, as follows:

INSERT INTO towns (id, country_fk, name)
SELECT 1, countryID, 'London' FROM countries WHERE country = 'UK';
Daniel Vassallo
30 seconds, gosh
vittore
@vittore: We call it the "fastest gun in the west" problem: http://meta.stackoverflow.com/questions/9731/fastest-gun-in-the-west-problem
Daniel Vassallo
grazzi siehbi :o)
mouthpiec
@mouthpiec: Hey, what a surprise to meet a compatriot! :)
Daniel Vassallo
well, you weren't the "fastest" in this thread ;)
stereofrog
@stereofrog: ...but faster from the other "exactly the same" answer(s) :)
Daniel Vassallo
indeed, INSERT ... SELECT is more nice here. +1
zerkms
+1  A: 
insert into towns(id, countrt_fk, name)
select 1 , countrt_fk , 'London' from Countries where country = 'UK'
vittore