Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown column error in this COUNT MySQL statement?

Tags:

sql

mysql

Error is

Unknown column 'num' in 'where' clause

SELECT COUNT(*) AS num, books_bookid
FROM bookgenre_has_books
WHERE num > 10
GROUP BY books_bookid

What am I doing wrong? Thanks.

like image 220
Ethan Allen Avatar asked Oct 21 '13 18:10

Ethan Allen


2 Answers

WHERE clause cant see aliases,use HAVING.

It is not allowable to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed

http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

like image 191
Mihai Avatar answered Sep 28 '22 15:09

Mihai


Try this, you should use the HAVING clause

SELECT COUNT(*) AS num, books_bookid
FROM bookgenre_has_books
GROUP BY books_bookid
HAVING COUNT(*) > 10

The SQL HAVING clause is used in combination with the SQL GROUP BY clause. It can be used in an SQL SELECT statement to filter the records that a SQL GROUP BY returns.

like image 42
Esteban Elverdin Avatar answered Sep 28 '22 17:09

Esteban Elverdin