• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting Max Year

 
Skanda Raman
Ranch Hand
Posts: 205
Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I am doing a application where i have to join table A and Table B with ID field and based on Max year in Table B i need to display the Place of the user. I tried using below query, I am not getting as expected. Please advise me here.

TABLEA
-------

------------
ID | NAME | PLACE
1 | JOHN | AMERICA
2 | JOHN | LONDON

TABLE B
-------

ID | YEAR
1 | 2009
2 | 2011

SELECT MAX(A.ID), PLACE,NAME FROM A,B
WHERE
A.ID=B.ID GROUP BY PLACE,NAME;
 
Paul Clapham
Sheriff
Pie
Posts: 20164
24
MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From what you posted I can tell what the output of that query would be. But I can't tell what you expected it would be, because you didn't mention that. So asking us why the actual output is different from what you expected isn't really fair. Don't you agree?
 
m coffee
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One way that would work is like this:

select a.personname, a.place, c.maxpersonyear
from tablea a,
(select a.personname, max(b.personyear) as maxpersonyear , max(b.id) as maxid
from tablea a, tableb b
where a.id = b.id
group by a.personname) c
where a.personname = c.personname and a.id = c.maxid
group by a.personname, a.place, c.maxpersonyear

However -- using id this way seems odd to me. You're assuming that the maximum id is also the last year. You should have a real date, not just year, because presumably someone can be in 2 places in a single year. If you have a real date, then you might have to manipulate this more to get the id which goes with that real date, and join that id to your tablea.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic