0

I am working on a results table at the minute, I am wanting to sort a table, by points (highest at the top), if points are equal I want to sort by goal difference, and then if goal difference is equal I want to sort by goals scored.

So a table may look like this,

+--------+--------+----------+-----------------+--------+
|  Team  | Scored | Conceded | Goal Difference | Points |
+--------+--------+----------+-----------------+--------+
| Team A |     20 |       10 | +10             |     15 |
| Team B |     20 |       15 | +5              |     15 |
| Team C |     10 |       10 | 0               |      9 |
| Team D |      5 |       5  | 0               |      9 |
+--------+--------+----------+-----------------+--------+

So Team A wins the league because it has a better goal difference than Team B, Team C finish above Team D because they score more goals, and all other things are equal.

Is it possible to order this way in mysql, or will I need to parse the results with PHP?

2

3 Answers 3

4

Guess what, you can pass multiple column names to ORDER BY

SELECT * FROM mytable ORDER BY Points DESC, `Goal Difference` DESC, Scored DESC 

You haven't given your table structure, but as pointed out by jpg if these fields are not numeric, ORDER by field_name + 0 may be more appropriate

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

3 Comments

You've forgot about Points ;)
In case that Goal Difference may be char or varchar, `Goal Difference` + 0 will be better. :-D
Agreed @JPG but you know how these fastest gun of the west answers are shoot first edit later :) but there were a couple of others that needed shooting :)
1

You can do like this using query

SELECT * from `your_table` ORDER BY points DESC, goal_difference DESC, scored DESC

Comments

0

You can order by multiple columns at the same time.

SELECT some_cols
FROM table
WHERE (some conditions)
ORDER BY col1 DESC, col2, col3;

Comments

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.