我正在尝试连接两个表,一个图像表和一个喜欢/不喜欢的表。我需要按百分比计算每个图像和订单的喜欢百分比。找到当前项目并返回下一个项目。
所以我将其分解为几个查询,首先我找到当前图像的百分比。
然后第二个是我完全混淆的地方:
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子句中无法识别出错误说明不喜欢。
答案 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