"advanced maths" in queries

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Flamie
Forum Contributor
Posts: 166
Joined: Mon Mar 01, 2004 3:19 pm

"advanced maths" in queries

Post by Flamie »

So heres the deal, in my code I have:

Code: Select all

$posx; //player's X position
$posy; //player's Y position
Now in my database, in my player table theres a posx and posy position.

Now I have a viewport of 550x350 pixels which is peg registered (player is always centered).
Now to grab the other players right now I do a simple query and grab all the players whos posx and posy are within that 550x350 rectangle around you.
One problem with that is that it doesnt return them in order of distance from you.
I was thinking of changing that query to order by distance, which would mean SQRT( ($posx - posx)^2 + ($posy - posy)^2), now heres my question:
is it ok to do a query where "distance" is less than 275, ordered by distance? Or would that slow down the query a lot?
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

Keep your code as it is at the moment where you're only returning players within the viewport, but add the distance equation to the fields returned and order by it. That way you'll only be calculating the distance of visible players instead of all the players. Much more scalable.
User avatar
Vikas Jayna
Forum Newbie
Posts: 3
Joined: Tue Apr 11, 2006 1:17 am

Post by Vikas Jayna »

It certainly will add some overhead to the query as the computations will be done for every record in the result set and then the ordering would be done. What would be number of players within another players viewport at any given point of time? Unless this number is huge, there should be no issues with the query in terms of speed.
Post Reply