使用 MAX 和 MIN 计算字段的分数

Calculating the score of fields using MAX and MIN

查询的objective简而言之就是根据分数列出所有帖子,分数是根据日期、浏览量和评分

的计算分数计算得出的
 SELECT
          p.id
         , p.date
         , p.title
         , r.module
         , r.module_id
         , IFNULL(v.total_views,0)  AS views
         , r.total_rating           AS rating

     #the following formula calculates the Score 10*(MAX(points)-(points))/(MAX(points)-MIN(points))

    , round((round(10-(((PD.MaxDate-p.date)/(PD.MaxDate-PD.MinDate))*10), 3) + round(10-(((MAX(v.total_views)-v.total_views)/(MAX(v.total_views)-MIN(v.total_views)))*10), 3) + round(10-(((MAX(r.total_rating)-r.total_rating)/(MAX(r.total_rating)-MIN(r.total_rating)))*10), 3))/3, 3) AS Score


  FROM  posts p

  LEFT  JOIN ( SELECT ra.module_id
              , ra.module   AS module
              , SUM(ra.ilike)    AS total_rating
           FROM rates ra
          WHERE ra.module = 'posts'
          GROUP
             BY ra.module_id
       ) r ON r.module_id = p.id

  LEFT  JOIN ( SELECT pv.post_id
              , SUM(1)    AS total_views
           FROM posts_views pv
          GROUP
             BY pv.post_id
       ) v ON v.post_id = p.id

   JOIN (SELECT MIN(date) AS MinDate, MAX(date) AS MaxDate FROM posts) PD


    ORDER BY Score DESC

查询的问题是它只给出 1 行结果而不是显示所有帖子。

我认为问题在于使用 MAX() 和 MIN() 时没有将其与用于获取评级和视图的 SUM() 的 LEFT JOIN 查询分开。

MCVE http://sqlfiddle.com/#!9/70d1ec/1

答案是添加以下行感谢 Ivar Bonsaksen:

JOIN ( SELECT MAX(t.total) AS max_views, MIN(t.total) AS min_views FROM ( SELECT COUNT(*) as total FROM posts_views GROUP BY post_id ) t ) mv
JOIN ( SELECT MAX(t.total) AS max_rates, MIN(t.total) AS min_rates FROM ( SELECT COUNT(*) as total FROM rates GROUP BY module_id ) t ) mr