sql查询最大值属性1和distinct attibute属性2,带有双条目过滤器

7vux5j2d  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(385)

我希望有人能帮助我的sql查询。
我有一张这样的table:
我喜欢更多的东西。。。
1 | 1000 | 5 | ...
2 | 1000 | 20 | ...
3 | 1001 | 7 | ...
4 | 1002 | 11 | ...
5 | 1003 | 19 | ...
6 | 1003 | 19 | ...
7 | 1003 | 18 | ...
8 | 1004 | 17 | ...
9 | 1005 | 6 | ...
现在我需要把它们过滤成max likes和distinct post id。
我发现这个代码,但它不是100%工作在我的情况下。它给了我最大的喜欢和不同的职位id´但只有一次r和最大值不同。如果同一个条目有r 3次,则它将不明显。我需要过滤掉一次。希望有人能帮忙。

SELECT p.*
    FROM posts p
    INNER JOIN
        (SELECT post_id, MAX(likes) AS MaxLikes
        FROM posts
        GROUP BY post_id) grouped 
    ON p.post_id = grouped.post_id 
    AND p.likes = grouped.MaxLikes
    ORDER BY p.post_id ASC

结果如下:
我喜欢更多的东西。。。
2 | 1000 | 20 | ...
3 | 1001 | 7 | ...
4 | 1002 | 11 | ...
5 | 1003 | 19 | ...
6 | 1003 | 19 | ...
8 | 1004 | 17 | ...
9 | 1005 | 6 | ...

yhqotfr8

yhqotfr81#

试试这个

Select max(id) as id, post_id, likes
From posts
Where (post_id, likes) in (Select  post_id, max(likes) from posts group by post_id)
group by post_id, likes
pn9klfpd

pn9klfpd2#

你需要 subquery 采用相关法:

select p.*
from posts p
where p.likes = (select max(p1.likes) from posts p1 where p1.post_id = p.post_id);
kqlmhetl

kqlmhetl3#

如果您使用的是mysql 8+,可以尝试以下方法:

Select * from
(Select *, Row_Number() over (partition by post_id order by likes desc) as ranking)c
where ranking = 1

相关问题