MySQL foreach?

I have two database tables, users and logs. I need SQL code to do something in rows

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

I could use php to implement foreach, but I decided it was probably a pure SQL way. I am using a MySQL server if this helps.

+3
source share
2 answers

try a template like this

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

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

+6
source

Try:

INSERT INTO logs (user_id) SELECT id FROM users;

This will give you a clean entry logfor each user id.

+3
source

Source: https://habr.com/ru/post/1720228/


All Articles