我有以下表格:
帖子
| id | message |
| 1 | a message |
| 2 | another message |
posts_summaries
| post_id | datetime | param | value |
| 1 | 2016-06-06 09:01:09 | like | 100 |
| 1 | 2016-06-06 09:01:11 | reach | 700 |
| 1 | 2016-06-06 09:01:07 | comments | 80 |
| 1 | 2016-06-06 10:01:06 | like | 180 |
| 1 | 2016-06-06 10:01:12 | reach | 1200 |
| 1 | 2016-06-06 10:01:09 | comments | 92 |
| 2 | 2016-06-06 09:01:09 | like | 94 |
| 2 | 2016-06-06 09:01:11 | reach | 600 |
| 2 | 2016-06-06 09:01:07 | comments | 50 |
| 2 | 2016-06-06 10:01:06 | like | 133 |
| 2 | 2016-06-06 10:01:12 | reach | 1100 |
| 2 | 2016-06-06 10:01:09 | comments | 93 |
每个小时,每个帖子的当前数据都存储在post_summaries表中。 现在我想只加载帖子中的最新数据。所以对于帖子2来说就是
| 2 | 2016-06-06 10:01:06 | like | 133 |
| 2 | 2016-06-06 10:01:12 | reach | 1100 |
| 2 | 2016-06-06 10:01:09 | comments | 93 |
我尝试使用以下方法执行此操作:
select param, value, MAX(date) from posts_summaries WHERE post_id = 2 GROUP BY param
但是这会返回具有最新日期的最旧数据,因此:
| 2 | 2016-06-06 10:01:06 | like | 94 |
| 2 | 2016-06-06 10:01:12 | reach | 600 |
| 2 | 2016-06-06 10:01:09 | comments | 50 |
所以它给了我2016-06-06 09的行,但是日期2016-06-06 10。
我可以使用什么查询来获取post_id = 2
的每个参数的最新数据提前致谢!
答案 0 :(得分:1)
一种方法是使用where
子句获取每个参数的最后一个值:
select ps.*
from post_summaries ps
where ps.post_id = 2 and
ps.datetime = (select max(ps2.datetime)
from post_summaries ps2
where ps2.post_id = ps.post_id and ps2.param = ps.param
);
如果你知道总有三个参数并且它们被插在一起,那么这就容易了:
select ps.*
from post_summaries ps
where ps.post_id = 2
order by ps.datetime desc
limit 3;