Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql Foreach Loop Syntax

Tags:

mysql

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)

like image 782
user2306941 Avatar asked Mar 05 '26 02:03

user2306941


1 Answers

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'
like image 153
juergen d Avatar answered Mar 06 '26 17:03

juergen d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!