来自2个表的MySQL SELECT获取最新记录

时间:2020-04-21 20:36:35

标签: mysql sql

查询有问题。我的数据库表格:

第一张桌子

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 

第二张表

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

例如帖子和评论。我想发表最新的评论。

预期输出:

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

我的查询

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

输出:

 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

我尝试使用MAX(date_add),但不起作用,或者我做错了事

1 个答案:

答案 0 :(得分:0)

您可以对DType x; DType* ptr = &x; DType** ptrptr = &ptr; std::cout << ptr << '\n'; // some address will be printed // setting a pointer a pointer is pointing to, to nullptr by dereferencing the // pointer-pointer *ptrptr = nullptr; std::cout << ptr << '\n'; // nullptr representation (0) printed 语句中的MAX()date_add ed GROUP使用BY notification_id聚合的子查询:

JOIN

Demo

相关问题