Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL foreach?

Tags:

sql

mysql

I have two database tables, users and logs. I need SQL code to do something along the lines of

foreach(id in users)
  insert into logs a record with user_id = id;
endforeach;

I could use php to implement the foreach but I figured there is probably a pure SQL way of doing this. I'm running a MySQL server if that helps.

like image 963
sjobe Avatar asked Dec 18 '25 00:12

sjobe


2 Answers

try a pattern similar to this

INSERT INTO logs (blah,blah)
SELECT foo,bar from Users 

You should also read into something called Correlated subqueries if you need some type of logical connection between the two statements

like image 142
keithwarren7 Avatar answered Dec 19 '25 18:12

keithwarren7


Try:

INSERT INTO logs (user_id) SELECT id FROM users;

That will give you a blank log record for every user ID.

like image 36
richsage Avatar answered Dec 19 '25 18:12

richsage



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!