2

I want to execute a MYSQL query:

INSERT INTO taskattempts (taskID) VALUES (_);

which I want to execute multiple times, once for each result of the query:

SELECT id FROM tasks WHERE stageID = 1;

using the resultant id from the second query as the value of taskID in the first.

Is there any way to do this using a single MySQL query? A PHP loop running multiple queries seems dreadfully inefficient.

*EDIT *

I actually need to fill in multiple columns, two static and one with the subquery. I found that INSERT INTO taskattempts (stageAttemptID, taskID, complete) SELECT 0, id, 5 FROM tasks WHERE stageID = 5; works, but wonder whether this is kosher. Also, in the interest of knowledge, can you fill in different columns with different queries?

1 Answer 1

4
 INSERT INTO taskattempts (taskID) SELECT id FROM tasks WHERE stageID = 1;

(This is universally supported standard SQL).

In response to the second part of the question, you can freely mix constants and columns in the SELECT clause:

 INSERT INTO taskattempts (stateAttemptID, taskID, complete) 
    SELECT 0, id, 5 FROM tasks WHERE stageID = 1;

If your constants are strings, don't forget to quote them. And remember, you can include a complex SELECT statement with JOINs and aggregation if required.

Sign up to request clarification or add additional context in comments.

2 Comments

Well that was simple. Though, in an effort to simplify my question, I've missed something. I actually need to fill in multiple columns, two static and one with the subquery. I found that INSERT INTO taskattempts (stageAttemptID, taskID, complete) SELECT 0, id, 5 FROM tasks WHERE stageID = 5; works, but wonder whether this is kosher. Also, in the interest of knowledge, can you fill in different columns with different queries?
@wyatt if u miss something in your question edit the question . dont use comments for extending the question.

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.