表结构如下
每个用户有多条数据,查询前 8 个用户点击量最多的一条数据,再按照点击量倒序,这个 sql 怎么写,谢谢!
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
1
cxbig 2016-10-21 18:56:17 +08:00 via iPhone
SELECT data_name, count(hits)
FROM table GROUP BY data_name ORDER BY count(hits) DESC |
3
lishunan246 2016-10-21 19:30:52 +08:00
select distinct
|
4
kfll 2016-10-21 19:37:03 +08:00 via iPhone 1
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
这样? |
5
akira 2016-10-21 19:52:30 +08:00 1
@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 |
6
neoblackcap 2016-10-21 19:59:38 +08:00
MySQL 没有 windows 函数,无法实现你想要的效果,若是仅仅选取 user_id 跟 hits 两个 field 倒是可以做到
|
7
Powered 2016-10-21 20:00:09 +08:00 1
@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 |
8
reus 2016-10-21 20:08:26 +08:00 1
如果支持 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 |