使用聚合别名的地方

时间:2018-02-21 11:00:53

标签: mysql sql aggregate-functions alias

此查询

select r1.name, count(stars) as reviewCount 
from (reviewer r1 join reviewer r2 using(rID)) join rating using(rID) 
group by r1.name;

产生以下输出

    +------------------+--------------+
    | name             | reviewCount |
    +------------------+--------------+
    | Ashley White     |            1 |
    | Brittany Harris  |            3 |
    | Chris Jackson    |            3 |
    | Daniel Lewis     |            1 |
    | Elizabeth Thomas |            2 |
    | James Cameron    |            1 |
    | Mike Anderson    |            1 |
    | Sarah Martinez   |            2 |
    +------------------+--------------+

我想列出有reviewCount>的用户3,如下所示

+------------------+--------------+
| name             | reviewCount |
+------------------+--------------+
| Brittany Harris  |            3 |
| Chris Jackson    |            3 |
+------------------+--------------+

我尝试过使用where和having子句但它们会导致Empty set (0.01 sec)

select r1.name, count(stars) as reviewCount 
from (reviewer r1 join reviewer r2 using(rID)) join rating using(rID) 
group by r1.name
having reviewCount > 3;

我错过了什么?

edit1:请参考this以获取要测试的样本数据

编辑2:也有人可以建议我如何在不使用计数和

的情况下编写此查询

1 个答案:

答案 0 :(得分:2)

结果实际上是正确的,但您的查询需要稍加修改。您需要使用>=而不是>

HAVING reviewCount >= 3;

我宁愿使用聚合列而不是它的别名,因为它适用于大多数RDBMS。

HAVING count(stars) >= 3