2
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 term. I tried to find a solution in many ways, but I failed in all of them. Usei group by, select MAX(vigencia) etc.
Any way to do this? I could treat the result by PHP, but if you can bring it like this with the query, I prefer.
Great! It worked perfectly. I tried everything but that. Thanks!
– morphinduction
Edgar, like I said before, it worked. But it turns out that in some cases it’s not working, bro. What gets dirty? I create a query in Sqlfiddle for you to see or put the information here, in the above question?
– morphinduction
@xmdenis make a fiddle and feed it with information to simulate the error.
– Edgar Muniz Berlinck