MySQL Paste with select subquery for single value

I have a MySQL insert request that should pull one data field from another table, and I was wondering if this can be done using the select subquery

INSERT INTO resources ( client_account_id, date_time, resource_name, resource_description_id, ) VALUES ( {0}, '{1}', '{2}', {3}, ) 

and I need a select query to get resource_description_id from another table

 SELECT resource_description_id FROM resource_descriptions WHERE resource_description = '{0}' 

I saw examples of duplication of whole tables, but I'm not sure how this can be done when only one field from another table is required, and the remaining fields from the form.

Thanks!

+6
source share
5 answers

In the subquery, you can simply select the desired values. Sort of:

 INSERT INTO resources ( client_account_id, date_time, resource_name, resource_description_id, ) SELECT {0}, '{1}','{2}', resource_description_id FROM resource_descriptions WHERE resource_description = '{3}' 
+8
source
 INSERT INTO resources ( client_account_id, date_time, resource_name, resource_description_id, ) VALUES ( {0}, '{1}', '{2}', SELECT resource_description_id FROM resource_descriptions WHERE resource_description = '{0}' ) 
+2
source
 INSERT INTO resources ( resource_description_id ) ( SELECT resource_description_id FROM resource_descriptions WHERE resource_description = '{0}' ) 
+1
source

You can do an insert using the select query results

 INSERT INTO resources ( client_account_id, date_time, resource_name, resource_description_id ) SELECT '{0}', '{1}', '{2}', resource_description_id FROM resource_descriptions WHERE resource_description = '{0}' 
0
source

MySQL did not like most of these queries unless I added parentheses around the subquery. Here is what I used.

 INSERT INTO resources ( client_account_id, date_time, resource_name, resource_description_id, ) VALUES ( '{0}', '{1}', '{2}', (SELECT resource_description_id FROM resource_descriptions WHERE resource_description = '{0}') ) 
0
source

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


All Articles