mysql 排序去重 sql 写法

2016-10-21 18:45:37 +08:00
 anai1943

表结构如下

data_id 主键

user_id

data_name

hits 点击量

每个用户有多条数据,查询前 8 个用户点击量最多的一条数据,再按照点击量倒序,这个 sql 怎么写,谢谢!

5203 次点击
所在节点    MySQL
8 条回复
cxbig
2016-10-21 18:56:17 +08:00
SELECT data_name, count(hits)
FROM table
GROUP BY data_name
ORDER BY count(hits) DESC
anai1943
2016-10-21 19:21:05 +08:00
@cxbig 您看下附言,我想查询的是这样的结果,谢谢!
lishunan246
2016-10-21 19:30:52 +08:00
select distinct
kfll
2016-10-21 19:37:03 +08:00
select * from (select user_id, max(hits) as max_hits from t group by user_id) t2 left join t on t.user_id = t2.user_id and t.hits = t2.max_hits

这样?
akira
2016-10-21 19:52:30 +08:00
@kfll
select t.* from (select user_id, max(hits) as max_hits from t group by user_id) t2 left join t on t.user_id = t2.user_id and t.hits = t2.max_hits

order by t.max_hits desc
limit 3
neoblackcap
2016-10-21 19:59:38 +08:00
MySQL 没有 windows 函数,无法实现你想要的效果,若是仅仅选取 user_id 跟 hits 两个 field 倒是可以做到
Powered
2016-10-21 20:00:09 +08:00
@akira

select t.* from (select user_id, max(hits) as max_hits from t group by user_id) t2 left join t on t.user_id = t2.user_id and t.hits = t2.max_hits

order by t2.max_hits desc
limit 3
reus
2016-10-21 20:08:26 +08:00
如果支持 window functions ,就很简单,好像 MariaDB 支持? postgres 支持,所以很方便

select * from (

select
*, row_number() over (patition by user_id order by hits desc) as r
from table

)
where r = 1
order by hits desc
limit 8

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

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

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

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

© 2021 V2EX