Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LEFT JOIN on Max Value

Suppose I have the following two tables:

STUDENT
studentid   lastname   firstname
1           Smith      John
2           Drew       Nancy

STUDENT_STORY
studentid   dateline   storyid   status
1           1328313600 10        2
1           1328313601 9         1
2           1328313602 14        2
2           1328313603 12        1

Now, I need an SQL query that would select each student along with the latest story for that student in the student story table.

I am trying this:

SELECT s.*, ss.*
FROM student AS s
LEFT JOIN (
    SELECT *
    FROM student_story
    WHERE student_story.studentid = s.studentid
    ORDER BY dateline DESC LIMIT 1
) AS ss ON (ss.studentid = s.studentid)

However, this query does not work. It complains about s.studentid being an unknown field in the where clause of the sub query.

Please suggest how I can achieve what I'm trying to do.

Thanks.

like image 686
akanevsky Avatar asked Feb 04 '12 21:02

akanevsky


People also ask

What does (+) mean in SQL join?

The plus sign is Oracle syntax for an outer join. There isn't a minus operator for joins. An outer join means return all rows from one table. Also return the rows from the outer joined where there's a match on the join key. If there's no matching row, return null.

How do you use Max in inner join?

If you want to use a different date column, just change that: SELECT fp. * FROM facebook_posts fp JOIN( SELECT id, MAX(updated_at) AS latestUpdate FROM facebook_posts GROUP BY id) t ON t.id = fp.id AND t.

Does LEFT join take null values?

This means that a left join returns all the values from the left table, plus matched values from the right table or NULL in case of no matching join predicate.

How do I find the maximum value of two tables in SQL?

select id from T1 where price in( select max(price) from( select max(price) as price from T1 union select max(price) as price from T2 union select max(price) as price from T3 ) temp ) union select id from T2 where price in( select max(price) from( select max(price) as price from T1 union select max(price) as price from ...


2 Answers

Try something like this:

SELECT
  s.*,
  ss.*
FROM
  student AS s
LEFT JOIN
  student_story AS ss
ON (ss.studentid = s.studentid)
WHERE ss.dateline = (
  SELECT
    MAX(dateline)
  FROM
    student_story AS ss2
  WHERE
    ss2.studentid = s.studentid
)
like image 50
Detheroc Avatar answered Oct 11 '22 19:10

Detheroc


SELECT 
    s.sale_id,
    s.created_at,
    p.created_at,
    DATEDIFF(p.created_at, s.created_at) AS days
FROM
    pos_sales s
        LEFT JOIN
    pos_payments p ON p.sale_id = s.sale_id
        AND
    p.created_at = (SELECT 
            MAX(p2.created_at)
        FROM
            pos_payments p2
        WHERE
            p2.sale_id = p.sale_id)
like image 5
Namal Avatar answered Oct 11 '22 19:10

Namal