2
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' 

我马上就选这个栏目,怎么不存在呢?

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

4

1 回答 1

4

对于聚合列(如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
...

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

于 2013-05-18T22:51:49.520 回答