MySql having 条件筛选语句

891 阅读1分钟
  • mysql 中的 having 也是条件筛选语句,跟 where 的含义一样,但是 having 只用于对 group by 分组的结果进行条件筛选,所以可以先看看 group by 分组

  • havingwhere 其实是一个意思,只是 having 跟在 group by 后面,where 跟在 from 后面。

  • 这里我就在 group by 分组 测试数据基础上往下写了。

mysql> select name, count(*) as 数量, avg(age) as 平均年龄 from test group by name;
+------+--------+--------------+
| name | 数量   | 平均年龄     |
+------+--------+--------------+
| NULL |      1 |         NULL |
| djy  |      1 |       5.0000 |
| dzm  |      1 |      20.0000 |
| xyq  |      2 |      20.0000 |
+------+--------+--------------+

平均年龄 > 10 的才显示
mysql> select name, count(*) as 数量, avg(age) as 平均年龄 from test group by name having avg(age) > 10;
+------+--------+--------------+
| name | 数量   | 平均年龄     |
+------+--------+--------------+
| dzm  |      1 |      20.0000 |
| xyq  |      2 |      20.0000 |
+------+--------+--------------+

wherehaving 也是可以同时存在的,先通过 where 过滤在通过分组之后 having 过滤
mysql> select name, count(*) as 数量, avg(age) as 平均年龄 from test where name='dzm' group by name having avg(age) > 10;
+------+--------+--------------+
| name | 数量   | 平均年龄     |
+------+--------+--------------+
| dzm  |      1 |      20.0000 |
+------+--------+--------------+