简体   繁体   中英

Optimal query - any way to avoid hundreds of queries in loop?

I want to save top 100 results for a game daily.

I have two tables: Users, Stats.

Users db has two columns: userID (mediumint(8) unsigned AUTO_INCREMENT) and userName (varchar(500)).

Stats db has three columns: time (date), userID (mediumint(8) unsigned AUTO_INCREMENT), result (tinyint(3) unsigned).

Now, every time I execute query (daily) I have array of 100 results wit user name. So here's what I need to do:

For every result in array:

  1. get user id from Users table - or if user doesn't exist in User table than create entry and get id;
  2. Insert to Stats table current date, user id and and result.

What would be the most optimal way to do this in php and mysql. Is there a way to avoid having 200 queries in 'for' loop.

Thanks for your time guys.

  1. 200 queries par day is nothing. You can leave everything as is and there will be not a single problem.

  2. why do you have an array with user names where you ought to have user ids instead?

  3. Mysql INSERT query support multiple VALUES statement. So, you could assemble a string like

    VALUES (time,userid,result),(time,userid,result),(time,userid,result)

and run it at once.

Also note that userID should be int, not medium int and in the stats table it shouldn't be autoincremented.

Use a pair of prepared statements . You'll still be running each one 100 times, but the query itself will already be parsed (and even cached by the DB server), it'll just have 100 different sets of parameters to be run with, which is quite efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM