简体   繁体   English

如何 select 1 行每个条件

[英]How to select 1 row each condition

Input data :输入数据

npost_id npost_id mid like_count点赞数
7 7 t4 t4 3 3个
21 21 t11 t11 2 2个
30 30 t16 t16 2 2个
31 31 t16 t16 2 2个
32 32 t18 t18 2 2个

I want the post_id that received the most likes per one person.我想要每个人获得最多赞的 post_id。

I need to pick only one row with satisfying several conditions: Max(like_count), per 1 id (Can be duplicated), npost_id (primary key)我只需要选择满足几个条件的一行:Max(like_count), per 1 id (Can be duplicated), npost_id (primary key)

Here's what I've tried:这是我尝试过的:

SELECT npost_id, mid, like_count 
FROM feed
WHERE (mid, like_count) IN (SELECT mid, MAX(like_count) 
                            FROM feed
                            GROUP BY mid)

I can't think of anything other than that query.除了那个查询,我想不出其他任何东西。

In MySQL 8.0, one option to retrieve only one row for each combination of <mid, like_count> is to use the ROW_NUMBER window function, which allows you to assign a ranking value for each combination of <mid, like_count> (a partition).在 MySQL 8.0 中,为 <mid, like_count> 的每个组合只检索一行的一个选项是使用ROW_NUMBER window function,它允许您为 <mid, like_count> 的每个组合(一个分区)分配一个排名值。 In order to get only one element for each of these, it's sufficient to filter out rows that have ranking bigger than 1 (the rows that have repeated <mid, like_count> values).为了只为其中的每一个获取一个元素,过滤掉排名大于 1 的行(重复 <mid, like_count> 值的行)就足够了。

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY mid, like_count ORDER BY npost_id) AS rn
    FROM tab
)
SELECT npost_id, mid, like_count
FROM cte
WHERE rn = 1

Check the demo here .此处查看演示。


In MySQL 5.7, you can instead aggregate on the two different combination of <mid, like_count> and take the smaller value for the npost_id field (given that you are willing to accept any npost_id value for the partition).在 MySQL 5.7 中,您可以在 <mid, like_count> 的两个不同组合上进行聚合,并为 npost_id 字段取较小的值(前提是您愿意接受分区的任何 npost_id 值)。

SELECT MIN(npost_id) AS npost_id, 
       mid, 
       like_count
FROM tab
GROUP BY mid, like_count

Check the demo here .此处查看演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM