In my rankings
database I have a table named times
. I also have another table with authors. The authors have author id's (named ath_id
inside the times
table).
Records saved in times
table:
id ath_id brand_id time date
------------- ------------ -------------- -------------- --------------
65125537 5384729 3 44741 May 8 2014
72073658 4298584 1 1104 Jun 28 2015
86139060 4298584 2 2376 Nov 20 2016
92237079 4298584 1 1115 Jun 24 2017
92237082 4298584 1 1104 Jun 24 2017
93436362 5384729 12 376492 Dec 31 2012
What I want to achieve
I'd like to retrieve an ordered list of the times that belong to the author (by the author id). I'd like to order them by brand_id
, and I only want the records with the lowest time
value.
Also, when there are multiple records with the same brand_id
and the same time
value, I'd like the list to be ordered by date. So the record with the latest date will be last.
What I have
I currently use this query: SELECT * FROM times WHERE ath_id = 4298584 GROUP BY brand_id ASC
.
It works great, but it limits records with the same brand_id
to 1, and thereby it limits records with the same time
, even when multiple records have the lowest time
value.
To sum it up
So in the case of the example above. When I select all the records with ath_id = 4298584
, I'd like to retrieve the following ordered list:
id ath_id brand_id time date
------------- ------------ -------------- -------------- --------------
72073658 4298584 1 1104 Jun 28 2015
92237082 4298584 1 1104 Jun 24 2017
86139060 4298584 2 2376 Nov 20 2016
This is my first time doing a bit more advanced SQL queries. I'm working with Laravel, so giving both a raw SQL solution and a Laravel solution using the Laravel Query Builder wouldn't do any harm.