3

I have a table 'posts' that has all info about my posts. I want to insert a new row into a different table for all posts that are of type 'public'. I want to run a query that would look something like this:

$ids = (SELECT post_id FROM posts WHERE post_type = 'public')    
foreach($id in $ids){
    INSERT INTO new_posts (post_id, post_data) VALUES ($id, 'hello');
}

I know I can insert multiple rows in one sql statement, but I need the post_id to change for each one and there are too many for me to change it manually.

What is the correct mysql syntax for this that I can run in my database manager? (Adminer)

1 Answer 1

11

You don't need a loop. You can do it in one query

INSERT INTO new_posts (post_id, post_data)
SELECT post_id, 'hello'
FROM posts 
WHERE post_type = 'public'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Worked like a charm!

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.