MySQL INSERT query

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

then use the found value in

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

Is it possible?

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

+3
source share
3 answers

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';
+5
source

You can use a subquery:

INSERT into towns (id, country_fk, name)
values (1, (SELECT countryID from countries where country = 'UK'), 'London')
+1
source
insert into towns(id, countrt_fk, name)
select 1 , countrt_fk , 'London' from Countries where country = 'UK'
+1
source

Source: https://habr.com/ru/post/1739381/


All Articles