Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Insert with select subquery for one value

Tags:

mysql

I have a MySQL insert query which needs to pull one data field from another table and I was wondering if this can be done with a 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 the resource_description_id from another table

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

I have seen examples for duplicating entire tables, but I'm not sure how this can be done when just one field is needed from another table and the other fields come from a form.

Thanks!

like image 830
mike Avatar asked Mar 12 '12 17:03

mike


People also ask

Can you use a subquery in an insert statement?

A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT , INSERT , UPDATE , or DELETE statement, or inside another subquery.

Can we use Insert and select together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

What is the difference between select into and insert into?

INSERT INTO SELECT vs SELECT INTO: Both the statements could be used to copy data from one table to another. But INSERT INTO SELECT could be used only if the target table exists whereas SELECT INTO statement could be used even if the target table doesn't exist as it creates the target table if it doesn't exist.

Can we use subquery in where clause in MySQL?

In MySQL subquery can be nested inside a SELECT, INSERT, UPDATE, DELETE, SET, or DO statement or inside another subquery. A subquery is usually added within the WHERE Clause of another SQL SELECT statement. You can use the comparison operators, such as >, <, or =.


1 Answers

Your subquery can just SELECT the values it needs. Something like:

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}'
like image 101
Jim Avatar answered Oct 05 '22 18:10

Jim