这个需求能用一条 sql 完成吗?

2017-08-11 09:43:38 +08:00
 klausgao
一个用户发帖的 table,能用一条 sql 选出每个用户最新的那条帖子吗?
例如 table 里的数据:
id userName post postDate
1 AA content1 2017-1-1
2 AA content2 2017-1-2
3 BB content3 2017-1-3
4 BB content4 2017-1-4

sql 选择后,得到结果集:
id userName post postDate
2 AA content2 2017-1-2
4 BB content4 2017-1-4

想了几天,不得其解。
4028 次点击
所在节点    程序员
27 条回复
jeffpan
2017-08-11 14:58:20 +08:00
SELECT max(login_time) ,user_id ,browser from tb_system_user_login_log group by user_id
我本地有个类似表,好像这样是可以的。
Buffer2Disk
2017-08-11 15:02:30 +08:00
@daimazha 的思路不错,但是如果 id 不是自增的,而是通过 uuid 生成的,这个时候下面这个方法可以解决问题。


select b.*
from (
select
max(post_date) as post_date,
user_name
from article
group by user_name) as a
inner join article b ON a.post_date = b.post_date AND a.user_name = b.user_name;

把用户的名字和发帖时间作为一个联合主键来处理。
daemonghost
2017-08-11 16:21:14 +08:00
先按用户名分组,然后再按日期排序,选取指定个数就行了
beginor
2017-08-11 16:39:31 +08:00
最佳的方案是 `row_number` + `partition` , 但是 MySQL 不支持
finull
2017-08-11 21:09:55 +08:00
select * from table t where not exists ( select * from table where userName = t.userName and postDate > t.postDate );

不要用聚合什么的
lenmore
2017-08-12 10:34:29 +08:00
终极做法是:
当用户发帖时,将最新的 ID 记录到用户表或者单独的一张表。更极端一点把标题时间都冗余了。
查询时 Join 帖子。
tsotsi
2017-08-12 15:06:18 +08:00
```sql
select *,if(@lastOne=userName,'',@lastOne:=userName) flag from (select * from table order by userName,postDate desc) a,(select @lastOne :='')b where flag <> ''
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/382102

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX