where子句COUNT()中的SQL错误

时间:2015-08-21 18:59:11

标签: mysql sql

我正在创建一个聊天,我不希望任何包含5个以上报告的消息。报告存储在table reports

这是我的SQL:

SELECT *, 
   message_id                               AS current_id, 
   (SELECT Count(report_id) 
    FROM   reports 
    WHERE  report_messages_fk = current_id) AS report_count 
FROM   messages 
   INNER JOIN users 
           ON message_user_fk = users.id 
WHERE  report_count < 5 
ORDER  BY message_date ASC 
LIMIT  100 

此sql在没有WHERE report_count < 5的情况下工作,但没有使用它。

感谢任何帮助。

编辑:用WHERE

替换HAVING clause fixed the issue, thanks.子句

2 个答案:

答案 0 :(得分:0)

SELECT -- *, replace with appropriate column names
message_id AS current_id, 
Count(report_id) as report_count
FROM  messages 
INNER JOIN users ON messages.message_user_fk = users.id 
INNER JOIN reports on reports.report_messages_fk = messages.current_id
group by message_id
having Count(report_id) < 5 

您的查询已经通过在join表格中加入reports进行了修改。此外,您必须在having条款中包含您的条件。

答案 1 :(得分:0)

您应该使用HAVING代替WHERE来过滤已经处理过的结果。

来源: http://blog.sqlauthority.com/2007/07/04/sql-server-definition-comparison-and-difference-between-having-and-where-clause/