Skip to content
Advertisement

MySQL SELECT from 2 tables get newest records

I have a problem with query. My database tabels:

FIRST TABLE

Notification
id |  Subject  | date_add
---+ ----------+---------
 1 | Subject1 | 2020-04-01 12:06:00
 2 |  Subject2 | 2020-04-18 19:12:59
 3 |  Subject3 | 2020-04-21 13:46:01
 4 |  Subject4 | 2020-04-20 13:46:01 

SECOND TABLE

Notification_post
    id | user_id | notification_id | description | date_add as post_date
    ---+---------+--------+-------------+---------
     1 | 1        | 1      | Text 1      | 2020-04-19 12:06:00
     2 | 2        | 1      | Text 2      | 2020-04-20 19:12:59
     3 | 3        | 1      | Text 3      | 2020-04-21 19:44:36
     4 | 2        | 2      | Text 1      | 2020-04-21 19:48:24
     5 | 1        | 2      | Text 2      | 2020-04-21 19:55:00

For example like a Post and comments. I want newest comment in post.

Expected Output:

Notification_ID |User_id | Subject | description  | post_date
----------------+--------+---------+--------------+-------------
       1        |    3   |  Subject1 |    text 3  | 2020-04-21 19:44:36
       2        |    1   | Subject2  |   Text 2   |  2020-04-21 19:55:00

My query

SELECT * 
FROM notification n 
LEFT JOIN notification_post p ON p.notification_id=n.id 
GROUP BY p.notification_id 
ORDER BY p.date_add DESC

OUTPUT:

 Notification_ID |User_id | Subject | description  | post_date
 ----------------+--------+---------+--------------+-------------
       1             1     Subject1     Text 1        2020-04-19 12:06:00
       2             2     Subcject2    Text 1        2020-04-21 19:48:24

I tried with MAX(date_add) but don’t work or I do it something wrong

Advertisement

Answer

You can use a subquery with MAX() aggregation for date_add column GROUPed BY notification_id within JOIN statements :

SELECT p1.notification_id, p1.user_id, n.Subject, p1.description, p2.post_date
  FROM notification_post p1
  JOIN notification n 
    ON p1.notification_id = n.id
  JOIN ( SELECT notification_id, MAX(date_add) as post_date
           FROM notification_post  
          GROUP BY notification_id ) p2
    ON p2.notification_id = p1.notification_id  
   AND p2.post_date = p1.date_add

Demo

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement