Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL join left get MAX(date)

i have these tables :

  • notice
    • id INT
    • cdate DATETIME
    • ...

  • theme
    • id
    • name

  • notice_theme
    • id_notice
    • id_theme

I want to get the latest notices for each theme.

SELECT id_theme, n.id
FROM notice_theme
LEFT JOIN (
    SELECT id, cdate
    FROM notice
    ORDER BY cdate DESC
) AS n ON notice_theme.id_notice = n.id
GROUP BY id_theme

The result is not good. An idea ? Thanks.

like image 973
user2252137 Avatar asked Apr 06 '13 12:04

user2252137


People also ask

Can you use Max in SQL with date?

MAX function works with “date” data types as well and it will return the maximum or the latest date from the table.

Will LEFT join increases number of rows?

Left Outer Join returns all of the rows in the current data and all the data from the matching rows in the joined data, adding rows when there is more than one match. This can result in an expanded row count.

How many records does LEFT join return?

The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side, if there is no match.

Are left joins more efficient?

IS LEFT join slower than join? The LEFT JOIN query is slower than the INNER JOIN query because it's doing more work.


1 Answers

There are so many ways to solve this but I'm used to do it this way. An extra subquery is needed to separately calculate the latest cDate for every ID.

SELECT  a.*, c.*
FROM    theme a
        INNER JOIN notice_theme b
            ON a.ID = b.id_theme
        INNER JOIN  notice c
            ON b.id_notice = c.ID
        INNER JOIN
        (
            SELECT  a.id_theme, MAX(b.DATE_CREATE) max_date
            FROM    notice_theme a
                    INNER JOIN notice b
                        ON a.ID_Notice = b.ID
            GROUP   BY a.id_theme
        ) d ON  b.id_theme = d.id_theme AND
                c.DATE_CREATE = d.max_date
  • SQLFiddle Demo
like image 165
John Woo Avatar answered Sep 21 '22 02:09

John Woo