如何使用WHERE自定义字段(别名)?

时间:2012-07-19 10:29:29

标签: php mysql alias where-clause

如何完成这样的查询:

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

该查询产生错误#1054 - Unknown column 'cnt' in 'where clause'

这是因为WHERE适用于分组之前 我该如何解决这个问题?

表格结构:

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

为简单起见,从http://www.tizag.com/mysqlTutorial/mysqlcount.php借来的表结构。

1 个答案:

答案 0 :(得分:15)

您需要使用HAVING子句来过滤聚合查询产生的记录:

SELECT type, COUNT(name) as cnt FROM products GROUP BY type HAVING cnt > 0;