I have the tables drives, documents, and defenders:
Defenders
id | nome | cpf
1 | Nome 1 | 000000
2 | Nome 2 | 000000
3 | Nome 3 |
Drives
id | document_id | defender_id | data
1 | 123 | 1 | 2014-01-01
2 | 233 | 2 | 2013-05-02
3 | 453 | 1 | 2011-01-05
4 | 543 | 3 | 2014-05-20
5 | 454 | 1 | 2012-12-12
6 | 532 | 2 | 2011-11-05
Documents
id | vigencia | publicacao
123 | 2014-01-05 | 2014-01-05
233 | 2013-05-02 | 2013-05-02
453 | 2011-01-05 | 2011-01-05
543 | 2014-05-05 | 2014-05-15
454 | 2012-12-13 | 2012-12-13
532 | 2011-11-05 | 2011-11-05
And my select:
select d.nome, doc.vigencia from defenders d
join drives dr on dr.defender_id = d.id
join documents doc on doc.id = dr.document_id
group by nome
order by nome, doc.vigencia desc, doc.publicacao desc, dr.data_hora desc
I need to return something like:
id | nome | vigencia
1 | Nome 1 | 2014-01-05
2 | Nome 2 | 2013-05-02
3 | Nome 3 | 2014-05-05
That is, only one record of each defenders ordered by force. I tried to find a solution in many ways, but I failed at all. I used group by, select MAX, etc.
Any way to do this? I could handle the result by PHP, but if you can bring it like this with the query, I prefer it.