I’d like to combine several queries into as few as possible. This is for a video game I’m writing.
Note
-spawn_id is the id of an entity that creates the bad guy on the level at a given place on a map.
-* from spawns includes the spawn_id, max quantity of bad guys to spawn(quantity), and the type of bad guy to spawn (mob_id)to spawn them and an ID to tell it what type of bad guy to spawn
the game is online so Id rather minimize the number of queries
It would be nice if I could subtract count (number already in game) from quantity(maximum quantity to have in game) where spawn ID are the same and return that all together
Would be even better if I could return the spawn ID quantity to spawn and the type of bad guy together as one row like this
SELECT spawn_id, COUNT(*) as ‘count’ FROM game_moblist GROUP BY spawn_id”
returns…
spawn_id count
======== =====
1 2
TABLE spawns contains
spawn_id quantity mob_id level
======== ======== ====== =====
1 5 1 2
mob_id poitns to TABLE mobs which has
mob_id ...stats for mob_id
====== ===================
1 unique stats for mob#1
I’d like to return something like this:
spawn_id quantity_to_spawn mob_id ...stats for mob_id
======== ================= ======
1 3 1 unique stats for mob#1
which means I must insert 3 rows selected from mobs which I don’t mind doing a second query for so I can multiply stats by level to create a bad guy in the game that is level 2… essentially level 2 means the stats are twice as high as the number stored in ‘mobs’ table
Here is my code so far I could finish it but I’d rather try to reduce the number of queries first.
sql= "SELECT spawn_id, COUNT(*) as 'count' FROM game_moblist GROUP BY spawn_id"
connection.query(sql, function(err, spawncount, fields) {
sql= "SELECT * FROM spawns"
connection.query(sql, function(err, spawns, fields) {
for (i=0;i<spawns.length;i++){
if (spawns[i].next_spawn < new Date().getTime()){
for (j=0;spawncount.length;j++){
if (spawncount[j].spawn_id ==spawns[i].spawn_id&&spawncount[j].count<spawns[i].quantity){
quantity_to_spawn = spawns[i].quantity -spawncount[j].count
//fetch spawns[i].mob_id mob from mobs table
for(k=0;k<quantity_to_spawn;k++){
//multiply for level
//insert into moblist
}
}
}
}
}
});
});
1 Answer