mattrick
mattrick

Reputation: 3890

Sorting Both MySQL Columns and PHP Arrays

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.

Upvotes: 1

Views: 53

Answers (2)

AkiEru
AkiEru

Reputation: 788

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.

Upvotes: 2

ReallyMadeMeThink
ReallyMadeMeThink

Reputation: 1071

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

Upvotes: -1

Related Questions