这个需求能用一条 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

想了几天,不得其解。
4018 次点击
所在节点    程序员
27 条回复
daimazha
2017-08-11 09:52:34 +08:00
给你个思路:
select * from x where id in ( select max(id) from x group by name);
klausgao
2017-08-11 10:00:17 +08:00
谢谢,我去试试
@daimazha
HaoC12
2017-08-11 10:05:44 +08:00
@daimazha 应该是选出 postdate 最大的吧
klausgao
2017-08-11 10:05:45 +08:00
@daimazha 另外多问一句,我记得 in 的效率比较低,是不是这样呢?
klausgao
2017-08-11 10:06:22 +08:00
@HaoC12 稍微改一下就好了,@daimazha 给出的是思路。
LeeSeoung
2017-08-11 10:11:04 +08:00
select distinct id,userName,post,max(postDate)over(partition by id,userName,post) from xxx
LeeSeoung
2017-08-11 10:11:52 +08:00
前提 postDate 得是 date 类型的,不是的话自己转换下
ayumilove
2017-08-11 10:12:27 +08:00
子查询结果比较大,建议用 exists
ayumilove
2017-08-11 10:14:43 +08:00
要是 Oracle 6 楼 的好~
daimazha
2017-08-11 10:28:11 +08:00
@klausgao #2

子查询效率不是很高,
这个场景 in 和 exists 没区别,
id 自增,最大的就是最新的一条,用 postdata 不如用主键 id
daya0576
2017-08-11 10:28:28 +08:00
select * from (select * from <table> ORDER BY archiveTime DESC) as tmp GROUP BY tmp.userName
这样也行把, 但不知道效率如何.
CRVV
2017-08-11 10:32:49 +08:00
@ayumilove
跟 Oracle 有什么关系,除了 MySQL 和 SQLite,其它的数据库都支持
daya0576
2017-08-11 10:35:56 +08:00
如果有用**Django ORM**的同学可以参考这篇: https://changchen.me/blog/20170515/ele-interview-solution/
用 annotate 实现楼主想要的效果 ^_^
nullcc
2017-08-11 10:42:52 +08:00
select A.userName, postDate, post from table A
inner join
(select distinct userName, max(postDate) as maxPostDate
from table
group by userName) B
on A.userName = b.userName and A.postDate = B.maxPostDate

大概是这样
anoymoux
2017-08-11 10:50:45 +08:00
加一张表 latest_post(userid,postid)
ayumilove
2017-08-11 11:11:44 +08:00
@CRVV 恩,谢谢。 好多年没用过 mysql 了 ,还以为原生 不支持 over(partition by ~)
x7395759
2017-08-11 11:47:20 +08:00
加表是一个不错的想法,view 也行呀。
noNOno
2017-08-11 11:55:03 +08:00
select * from (select *,row_number over (partition by userName order by postdate desc ) as rn from table ) where rn=1

能用 rownumber 吧
syncher
2017-08-11 11:59:51 +08:00
又是一个 group
fxxkgw
2017-08-11 12:44:17 +08:00
order by 加 group by

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

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

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

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

© 2021 V2EX