SQL编写自定义查询

时间:2018-10-30 13:04:25

标签: mysql sql sql-query-store

我需要编写一个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
)

2 个答案:

答案 0 :(得分:3)

  • Derived Table中,您可以首先确定每个用户的最大值reading_countsGroup ByMax()
  • 现在,只需将此结果集连接到userreading_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 

答案 1 :(得分:0)

SELECT * 
FROM mytable
WHERE user IN
(SELECT user, max(reading_counts)
FROM mytable
GROUP BY user)