该查询的简要目的是根据其得分列出所有帖子,该得分是根据日期,观看次数和评分的计算得分来计算的
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()而不将其与用于获取Rating和Views SUM()的LEFT JOIN查询分开。
答案 0 :(得分: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