tags:

views:

46

answers:

1

I would like to order by date and then team in a MySQL query. It should be something similar to this:

SELECT * FROM games ORDER BY gamedate ASC, team_id

AND it should output something like this:

2010-04-12 10:20 Game 1 Team 1
2010-04-12 11:00 Game 3 Team 1
2010-04-12 10:30 Game 2 Team 2
2010-04-14 10:00 Game 4 Team 1

So that Team 1 is under each other on the same date, but separate on a new date

+5  A: 

Assuming that gamedate is a date field rather than a datetime field, that should work. If it's a datetime field, you would have to use something like date(gamedate) as the first ordering predicate:

SELECT * FROM games ORDER BY date(gamedate) ASC, team_id ASC
paxdiablo
Thanks! that worked, now i want it to be a little more specific, it should order by date first, than the earliest time, while taking in account that the teams should be together:right now it is:2010-04-12 10:30 Game 2 Team 12010-04-12 10:20 Game 1 Team 22010-04-12 11:00 Game 3 Team 22010-04-14 10:00 Game 4 Team 1so the first time of that given date should be above
Michael
That would be a pretty heinous piece of SQL :-) I would suggest doing that at the application level rather than the database level. In other words, get the data sorted by date and team, then re-order team-sets (multiple records sharing same date and team) within the date so that team-sets with earliest start times in their first records float to the front.
paxdiablo
Couldn't one do that using `ORDER BY DATE(gamedate) ASC, team_id ASC, gamedate ASC`? Of course, I might understand the question incorrectly, but this should order the set of games of a `team_id` according to time, but not globally.
nikc
No, I don't think so, @nikc. That would still sort team at a higher precedence than the first start time. In other words, if team 2 had their first game before team 1, team 1 would _still_ come first simply because the team has a higher priority in the sort order.
paxdiablo
@paxdiablo Do you know a way to do this in application level using php?first get all the games, then loop trough the games, then do something like if $game[$i]['team_id'] = $game[$i+1]['team_id'] then push both to a new array... it would be hard indeed
Michael
@Michael, my knowledge of PHP is limited (i.e., zero). But I still suspect it would be easier in a procedural language than a relational algebra :-)
paxdiablo
@paxdiablo: yes, that is what I was trying to say with the 'not globally' part.
nikc
@Michael: that is a second problem, alas a second question.
nikc