Results 1 to 2 of 2
  1. #1
    Join Date
    Aug 2009
    Posts
    1

    Unanswered: Help my brain on a select please !

    Hi I am hoping some of you nice poeple can spend a few mins to help me out.

    example:

    table 1: id, name

    table 2: id,table_1_id, date

    Table 2 holds multiple rows that link to table 1 on the fk table_1_id.

    My result set wants to be include just one row from table 2 which holds the latest date - (or even the max(id) )

    so if we have :

    table1:

    1, Jim

    table 2:
    1, 1, 01-01-2010
    2,1, 01-01-2009
    3,1, 01-01-2008

    I just want to be able to get a 1:1 on the join , and get just the table2 row 1 back....


    hope that makes sense?

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Code:
    SELECT t1.id
         , t1.name
         , t2.id
         , t2.date
      FROM table1 AS t1
    INNER
      JOIN ( SELECT table_1_id
                  , MAX(date) AS max_date
               FROM table2
             GROUP
                 BY table_1_id ) AS m
        ON m.table_1_id = t1.id
    INNER
      JOIN table2 AS t2
        ON t2.table_1_id = t1.id
       AND t2.date = m.max_date
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •