tags:

views:

68

answers:

2
+1  Q: 

MySQL foreach ?

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.

+4  A: 

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

keithwarren7
Can blah,blah be column names from the users table ? i.e. can they be foo and bar
sjobe
yes they can, and you could also introduce a where clause
keithwarren7
+3  A: 

Try:

INSERT INTO logs (user_id) SELECT id FROM users;

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

richsage