发布时间:2024-04-06 19:30:01
SQL HAVING 子句通常与 GROUP BY 子句一起使用,用来过滤 GROUP BY 子句返回的分组结果集。
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2
+----+------------+-----------------+--------------------------+-------------+-----------------+ | id | username | password | email | cellphone | ip | +----+------------+-----------------+--------------------------+-------------+-----------------+ | 1 | mozhiyan | 123456 | java@www.365tools.cn | 13112344444 | 113.96.109.117 | | 2 | fanhua | xyzabc | cplusplus@www.365tools.cn | 15028882233 | 117.25.156.179 | | 3 | greatman | 123abc | python@www.365tools.cn | 13290029028 | 125.64.104.35 | | 4 | xiaogun123 | hsdjs23ZX | c@www.365tools.cn | 19036895933 | 101.37.97.51 | | 5 | my_code | 19951206 | php@www.365tools.cn | 19234561234 | 103.133.176.211 | | 6 | guxiaonuan | xy232323 | javascript@www.365tools.cn | 13409873222 | 113.96.109.117 | | 7 | coder | 20200304shengri | python@www.365tools.cn | 15645990222 | 101.37.97.51 | | 8 | happy_gril | sd@@sd | c@www.365tools.cn | 19090903636 | 220.181.38.148 | +----+------------+-----------------+--------------------------+-------------+-----------------+统计同一个 IP 地址上的用户注册数,筛选出注册数大于 2 的结果集:
SQL> SELECT ip, COUNT( username ) AS total FROM user GROUP BY ip HAVING total >=2;执行结果:
+----------------+-------+ | ip | total | +----------------+-------+ | 101.37.97.51 | 2 | | 113.96.109.117 | 2 | +----------------+-------+