首页 > 解决方案 > SQL编写自定义查询

问题描述

我需要编写一个 SQL 查询,它为每个用户生成最受欢迎的故事的名称(根据总阅读次数)。以下是一些示例数据:

故事名称 | 用户 | 年龄 | 阅读计数
-----------|-------|-----|---------------
故事1 | 用户1 | 4 | 12
故事2 | 用户2 | 6 | 14
故事4 | 用户1 | 4 | 15

这是我到目前为止所拥有的,但我认为它不正确:

Select *
From mytable
where (story_name,reading_counts)
IN (Select id, Max(reading_counts)
      FROM mytable
      Group BY user
)

标签: mysqlsqlsql-query-store

解决方案


  • 派生表中,您可以首先确定每个用户的最大值reading_countsGroup ByMax()
  • user现在,只需将此结果集连接到和上的主表reading_counts,即可获取对应于reading_counts用户最大值的行。

尝试以下查询:

SELECT 
  t1.* 
FROM mytable AS t1 
JOIN 
(
  SELECT t2.user, 
         MAX(t2.reading_counts) AS max_count 
  FROM mytable AS t2
  GROUP BY t2.user 
) AS dt 
  ON dt.user = t1.user AND 
     dt.max_count = t1.reading_counts 

推荐阅读