SQL错误说来自COUNT的列不存在

时间:2013-05-18 22:41:05

标签: mysql sql count

SELECT c.review, m.category, u.username, i.item, i.item_id, m.cat_id, COUNT(rv.review_id) totalCount
FROM reviews AS c
LEFT JOIN review_vote as rv
   ON c.review_id = rv.review_id
LEFT JOIN users AS u
   ON u.user_id = c.user_id 
LEFT JOIN items AS i
   ON i.item_id = c.item_id
LEFT JOIN master_cat AS m
   ON m.cat_id = i.cat_id
WHERE LENGTH(c.review) > 50 AND m.category = 'Movies' AND totalCount > 2
GROUP BY rv.review_id
ORDER BY RAND()
LIMIT 1

我收到此错误:

#1054 - Unknown column 'totalCount' in 'where clause' 

我现在正在选择这个专栏,为什么它不存在?

我正在尝试随机选择表rv中列出(或投票2次或多次)的评论。此外,我不确定我是否正确使用GROUP BY

1 个答案:

答案 0 :(得分:3)

使用聚合列(如count()),您必须使用HAVING子句为其添加条件:

SELECT c.review, m.category, u.username, i.item, i.item_id, m.cat_id, COUNT(rv.review_id) totalCount
FROM reviews AS c
LEFT JOIN review_vote as rv
   ON c.review_id = rv.review_id
LEFT JOIN users AS u
   ON u.user_id = c.user_id 
LEFT JOIN items AS i
   ON i.item_id = c.item_id
LEFT JOIN master_cat AS m
   ON m.cat_id = i.cat_id
WHERE LENGTH(c.review) > 50 AND m.category = 'Movies'
GROUP BY rv.review_id
HAVING COUNT(rv.review_id) > 2 -- Added this line!
ORDER BY RAND()
LIMIT 1

某些数据库(包括mysql)允许您使用列别名,例如HAVING totalCount > 2,但使用该表达式适用于所有数据库。即对于mysql(至少),您可以将其编码为:

....
GROUP BY rv.review_id
HAVING totalCouunt > 2
...

但它不能移植到所有其他数据库。