mysql - Left Join most recent record, if one exists -


i have table of people, , want pull recent record of event, there may not one.

so problem though i'm left joining make sure i'm getting record each person, i'm bringing people have events because i'm pulling max of date criteria.

select * tbl_people left join tbl_events on     tbl_people.people_uid = tbl_events.people_uid tbl_people.active = 1 , (     select max(event_date) tbl_events     ) 

table people have following

people_uid 

table events have following

event_uid, people_uid, event_name, event_date 

like said, i'd output this:

jen, had baby, 7/10/2015 shirley susan megan, had baby, 8/5/2014 etc. 

i hope makes sense.

one way use correlated subquery in join checks there doesn't exists event same person later date:

select * tbl_people p left join tbl_events e      on p.people_uid = e.people_uid      , not exists (        select 1 tbl_events         e.people_uid = people_uid           , event_date > e.event_date     ) p.active = 1 

it might not efficient solution though; maybe limiting left joined set first better. (or come think of exists should better).

given sample data set like:

people_uid  event_uid   people_uid  event_name          event_date jen         1           jen         had baby          2015-07-10 jen         3           jen         bought horse      2013-07-10 shirley     null        null        null                null susan       null        null        null                null megan       2           megan       had baby          2014-08-05 megan       4           megan       had baby    2015-08-05 

this result:

people_uid  event_uid   people_uid  event_name          event_date jen         1           jen         had baby          2015-07-10 shirley     null        null        null                null susan       null        null        null                null megan       4           megan       had baby    2015-08-05 

using joins this:

select * tbl_people p left join (     select e.*      tbl_events e      join (        select people_uid, max(event_date) mdate         tbl_events group people_uid     ) on a.mdate = e.event_date , e.people_uid = a.people_uid  ) b on p.people_uid = b.people_uid  p.active = 1 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -