Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use WHERE for custom field (alias)?

How do I accomplish query like so:

SELECT type, COUNT(name) as cnt FROM products WHERE cnt > 1 GROUP BY type

That query produces error #1054 - Unknown column 'cnt' in 'where clause'

It's because WHERE applies before grouping.
How can I workaround this?

Table structure:

id      name                type        price
123451  Park's Great Hits   Music       19.99
123452  Silly Puddy         Toy         3.99
123453  Playstation         Toy         89.95
123454  Men's T-Shirt       Clothing    32.50
123455  Blouse              Clothing    34.97
123456  Electronica 2002    Music       3.99
123457  Country Tunes       Music       21.55
123458  Watermelon          Food        8.73

Table structure borrowed from http://www.tizag.com/mysqlTutorial/mysqlcount.php for simplicity.

like image 475
Kristian Avatar asked Dec 06 '22 13:12

Kristian


1 Answers

You need to use HAVING clause to filter the records resulting from aggregated query:

SELECT type, COUNT(name) as cnt FROM products GROUP BY type HAVING cnt > 0;
like image 126
Omesh Avatar answered Dec 10 '22 11:12

Omesh