2015-08-21 190 views
0

我正在創建一個聊天,我不想要任何帶有5個以上的報告的消息。報告存儲在table reports中。SQL語句where子句COUNT()

這是我的SQL:沒有WHERE report_count < 5

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條款和HAVING clause fixed the issue, thanks.

+0

什麼是它的投擲錯誤的具體信息?錯誤號碼? – asdf

+0

你不能在'where'子句中使用列別名。使用'having'子句insetad。 –

+0

這是錯誤代碼:#1054 –

回答

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 

您的查詢已被包括在reportsjoin以及修改。您還必須在having條款中包含您的條件。