1

I've recently been making a stats system that reads from a database of players and sorts them in various ways. As you can see it works great, but my main problem being is that I need to sort the "Games Played" and "K/D Ratio" columns. But these columns are not stored in the MySQL database, the "Games Played" column is calculated by adding the "Wins" and "Losses" column. Likewise, the "K/D Ratio" column is calculated by dividing "Kills" by "Deaths".

I am using this to sort stats: SELECT * FROM stats ORDER BY <filter> DESC LIMIT 100 OFFSET <index> However, I also need to sort the two columns mentioned above. What would be the best way to go about this? I'm trying to avoid moving it to an array, but if it is unavoidable, I suppose I'll have to.

3
  • 1
    You definitely want to try to do the sorting in the database, as this will be exponentially faster than sorting in the JavaScript engine. Commented Apr 2, 2015 at 4:28
  • The database engine was designed for, among other things, sorting data. Commented Apr 2, 2015 at 4:34
  • 1
    You're forcing the client to do it rather than the server to do it, which is bad practice. Also, either way it would need to query the server for each sort, which is redundant Commented Apr 2, 2015 at 5:04

2 Answers 2

2
SELECT *, (Wins + Losses) AS GamesPlayed, (Kills / IFNULL(Deaths, Kills)) AS KDRatio FROM stats ORDER BY GamesPlayed DESC LIMIT 100 OFFSET <index>

You don't even needed to calculate the total games played in PHP, MySQL can be done for you and also usable for sorting.

Sign up to request clarification or add additional context in comments.

Comments

-1
SELECT *,(kills_column/deaths_column) AS kdratio FROM stats ORDER BY kdratio DESC

1 Comment

You absolutely need to check for division by zero in your query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.