SQL 编写自定义查询

SQL writing custom query

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

story_name | user  | age | reading_counts
-----------|-------|-----|---------------
story 1    | user1 | 4   | 12
story 2    | user2 | 6   | 14
story 4    | user1 | 4   | 15

这是我目前所知道的,但我认为它不正确:

Select *
From mytable
where (story_name,reading_counts)
IN (Select id, Max(reading_counts)
      FROM mytable
      Group BY user
)
SELECT * 
FROM mytable
WHERE user IN
(SELECT user, max(reading_counts)
FROM mytable
GROUP BY user)
  • Derived Table, you can first determine the maximum reading_counts for every user (Group By with Max())
  • 现在,只需将此结果集连接到 userreading_counts 上的主 table,即可获取与用户最大值 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