按喜欢的百分比排序并返回下一行

时间:2015-07-21 22:01:57

标签: mysql

我正在尝试连接两个表,一个图像表和一个喜欢/不喜欢的表。我需要按百分比计算每个图像和订单的喜欢百分比。找到当前项目并返回下一个项目。

所以我将其分解为几个查询,首先我找到当前图像的百分比。

然后第二个是我完全混淆的地方:

SELECT *, 
   SUM(CASE WHEN liked = '1' THEN 1 ELSE 0 END) AS liked,
   SUM(CASE WHEN liked = '0' THEN 1 ELSE 0 END) AS disliked
       FROM images i 
   LEFT JOIN 
       image_like il ON i.image_id = il.like_image_id
   WHERE (liked/liked + disliked) > ?
       AND image_site_id = ?
   GROUP BY i.image_id
   ORDER BY (liked/liked + disliked) DESC
   LIMIT 1

我在WHERE子句中无法识别出错误说明不喜欢。

1 个答案:

答案 0 :(得分:2)

原因是您无法在where中使用与select相同级别的列别名。但是,无论如何,您的逻辑都在聚合值上,因此它属于having子句。

假设liked仅采用值0和1,您可以将查询编写为:

SELECT i.*, SUM(liked = 1) AS liked, SUM(liked = 0) AS disliked
FROM images i LEFT JOIN 
     image_like il
     ON i.image_id = il.like_image_id
WHERE image_site_id = ?
GROUP BY i.image_id
HAVING AVG(liked = 1) > ?
ORDER BY AVG(liked = 1) DESC
LIMIT 1