MySQL:按

时间:2015-11-15 16:40:37

标签: mysql sql

我有以下表格:

message_notification

 ________________________
| id | message   | user  |
|____|___________|_______|
|  1 |     10    |   1   |
|____|___________|_______|
|  2 |     11    |   1   |
|____|___________|_______|
|  3 |     12    |   1   |
|____|___________|_______|

消息

 _________________________________________
| id |    post   |         date           |
|____|___________|________________________|
| 10 |     10    |   15-11-2015 19:45:36  |
|____|___________|________________________|
| 11 |     20    |   15-11-2015 19:47:44  |
|____|___________|________________________|
| 12 |     10    |   15-11-2015 19:53:12  |  
|____|___________|________________________|

发表

 ________________
| id |  content  |
|____|___________|
| 10 |     XX    |
|____|___________|
| 20 |     XX    |
|____|___________|

我希望收到分组发布的通知,排序的帖子包含最新消息。

所以,我希望得到以下结果:

1. post #10    
2. post #20  

如果有人在帖子#20中写下新消息,结果将如下:

1. post #20   
2. post #10   

我尝试过以下查询,但似乎顺序不适用于group by或inner join

SELECT noti.*
FROM message_notification noti
INNER JOIN message mess ON mess.id = noti.message
INNER JOIN post ON post.id = mess.post
WHERE noti.user = 1
GROUP BY post.id
ORDER BY mess.date DESC

3 个答案:

答案 0 :(得分:1)

您没有使用任何功能。订购邮件和日期。 请记住SELECT子句中的所有列都必须在GROUP BY子句中。

答案 1 :(得分:1)

首先,您应该从message为每个日期过滤掉更晚的日期(最长日期) 帖子。 请试一试。

SELECT noti.*
FROM message_notification noti
INNER JOIN (SELECT message.* 
           FROM message
           INNER JOIN 
          (SELECT id,MAX(`date`) AS dater 
           FROM message 
           GROUP BY id) T ON T.`dater` = message.`date`) mess ON mess.id = noti.message
INNER JOIN post ON post.id = mess.post
WHERE noti.user = 1
GROUP BY post.id
ORDER BY mess.date DESC

希望这有帮助。

答案 2 :(得分:1)

您可以使用not exists仅为每个帖子选择最近的消息

select * from post p
join message m on m.post = p.id
join message_notification mn on mn.message = m.id
where mn.user = 1
and not exists (
    select 1 from message m2
    join message_notification mn2 on mn2.message = m2.id        
    where m2.post = m.post
    and mn2.user = 1
    and m2.date > m.date
)
order by m.date desc