Powered By Blogger

Monday, 9 January 2012

Query to find the latest address details based on created dated ( one person can have multiple addresses)

The person table structure is as follows:

CREATE TABLE person
(
  id         int(11) AUTO_INCREMENT,
  fname      varchar(100),
  lastname   varchar(100),
  PRIMARY KEY(id)
);
The address table structure is as follows:

CREATE TABLE address(id int(11) AUTO_INCREMENT,  person_id int(11), city varchar(100), state varchar(100), zip varchar(10), created_date datetime, PRIMARY KEY(id), CONSTRAINT  fk_person_id FOREIGN KEY (person_id) REFERENCES person(id) , KEY(person_id, created_date));

to increase the performance we can create the index as follows:
create index idx1 on address (person_id, created_date)

The query is as follows:

SELECT *,
      city,
      state,
      zip,
      created_date
 FROM (SELECT p.*,
              (SELECT id
                 FROM address
                WHERE person_id = p.id
               ORDER BY person_id DESC, created_date DESC
                LIMIT 1)
                 latest_adr_id
         FROM person p
   ) Z,
      address adr
WHERE Z.latest_adr_id = adr.id;