3

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
  • Have you considered using an auto-incremented field for the id of the town? Commented Mar 31, 2010 at 22:04

3 Answers 3

5

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';
Sign up to request clarification or add additional context in comments.

4 Comments

@vittore: We call it the "fastest gun in the west" problem: meta.stackexchange.com/questions/9731/…
@mouthpiec: Hey, what a surprise to meet a compatriot! :)
@stereofrog: ...but faster from the other "exactly the same" answer(s) :)
indeed, INSERT ... SELECT is more nice here. +1
1
insert into towns(id, countrt_fk, name)
select 1 , countrt_fk , 'London' from Countries where country = 'UK'

Comments

1

You can use subquery there:

INSERT into towns (id, country_fk, name)
values (1, (SELECT countryID from countries where country = 'UK'), 'London')

3 Comments

thanks zerkms, but I need to store the value once so that I can use it in multiple INSERTS (about 100)
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: the answer was missing the 'from' clause - are you getting any errors now?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.