7

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!

5 Answers 5

9

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

2 Comments

The problem with this answer is if resource_description is not a match, then you get nothing. Have you tried running your reply?
Well I have a form which a user submits resource name, description, and keywords, Before I insert into the resource table I insert into the resource description table, so the description will always match. But that makes me think there is the possibility of duplicate resource descriptions. Is there a way to pull the most recently inserted row from a table?
2
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}'
 )

Comments

1
INSERT INTO resources
(
     resource_description_id
)
(
SELECT resource_description_id 
FROM resource_descriptions 
WHERE resource_description = '{0}'
)

Comments

0

You can do an insert using the results of a select query

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}'

Comments

0

MySQL didn't like most of these queries unless I added parenthesis 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}')
)

Comments

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.