Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select with multiple IDs

Tags:

sql

I have an Address History table with three fields: EmpID, Address, AddrID.

Every time I add a new address, I also increment the Address ID (AddrID) by 1 for that particular employee.

EmpID | AddrID | Address
-------------------------------
 1    |     1  | 1234 First Ave
 1    |     2  | 2145 First Ave
 1    |     3  | 1111 First Ave

 2    |     1  | 1001 Second St
 2    |     2  | 1002 Second St
 2    |     3  | 1003 Second St
 2    |     4  | 2222 Second St

 3    |     1  | 3332 Third Lane
 3    |     2  | 3333 Third Lane

 4    |     1  | 4444 Fourth Way

How do I get the most recent address (highest Address ID) for each employee? Ideally, I should be able to return:

EmpID | AddrID | Address
-------------------------------
 1    |     3  | 1111 First Ave
 2    |     4  | 2222 Second St
 3    |     2  | 3333 Third Lane
 4    |     1  | 4444 Fourth Way

So far I have either returned too many results (ie, every Employee, every AddrID 1, and every Address associated with the two), or too few results (ie, every Employee with an AddrID 4 - just Employee 2).

I have tried using Distinct, Group By, Order By, Having, and Self-Joins to no avail.

What am I missing?

like image 490
Phillip Deneka Avatar asked Nov 18 '25 06:11

Phillip Deneka


1 Answers

You can use a subquery that gets the MAX() addrid for each empid:

select t1.empid,
  t1.addrid,
  t1.address
from table1 t1
inner join
(
  select max(addrid) addrid, empid
  from table1
  group by empid
) t2
  on t1.empid = t2.empid
  and t1.addrid = t2.addrid

See SQL Fiddle With Demo

The inner query will return the max addrid and the empid then you join your table to that result on those two values this will limit the records that get returned.

like image 121
Taryn Avatar answered Nov 20 '25 21:11

Taryn