SQLite HAVING
子句用于指定过滤分组的结果,并作为最终查询结果的条件。 WHERE
子句将条件放在选定的列上,而HAVING
子句指定的条件是由GROUP BY
子句创建的列分组上(使用HAVING
子句条件一定要作用在由GROUP BY
子句指定列上)。
SELECT查询中HAVING
子句的位置:
SELECT FROM WHERE GROUP BY HAVING ORDER BY
语法
SELECT column1, column2 FROM table1, table2 WHERE [ conditions ] GROUP BY column1, column2 HAVING [ conditions ] ORDER BY column1, column2
下面举个例子来演示如何使用HAVING
子句。假设有一个名为student
的表,并具有以下数据:
sqlite> select * from student; 1|Maxsu|27|Shengzhen|20000.0 2|Minsu|25|Beijing|15000.0 3|Avgsu|23|Shanghai|2000.0 4|Linsu|25|Guangzhou|65000.0 5|Sqlsu|26|Haikou|25000.0 6|Javasu|21|Shengzhen|18000.0 7|Linsu|27|Haikou|10000.0 8|Minsu|23|Guangzhou|5000.0 9|Maxsu|23|Shenzhen|9000.0 sqlite>
示例1:
下面查询name
的数量小于2
的所有记录,在查询之前,先来查询看看每个名字的数量 -
-- 名字的数量 SELECT name, count(name) as total_number FROM student GROUP BY name; -- `name`的数量小于`2`的所有记录 SELECT name, count(name) as total_number FROM student GROUP BY NAME HAVING COUNT(NAME) < 2;
执行上面语句,得到结果如下 -
-- 所有记录 sqlite> select * from student; 1|Maxsu|27|Shengzhen|20000.0 2|Minsu|25|Beijing|15000.0 3|Avgsu|23|Shanghai|2000.0 4|Linsu|25|Guangzhou|65000.0 5|Sqlsu|26|Haikou|25000.0 6|Javasu|21|Shengzhen|18000.0 7|Linsu|27|Haikou|10000.0 8|Minsu|23|Guangzhou|5000.0 9|Maxsu|23|Shenzhen|9000.0 sqlite> sqlite> -- 每个名字的数量 sqlite> SELECT name, count(name) as total_number FROM student GROUP BY name; Avgsu|1 Javasu|1 Linsu|2 Maxsu|2 Minsu|2 Sqlsu|1 -- 查询数量小于2的名字 sqlite> SELECT name, count(name) as total_number FROM student GROUP BY NAME HAVING total_number < 2; Avgsu|1 Javasu|1 Sqlsu|1 sqlite>
示例2:
下面查询address
的数量大于等于2
的所有记录,在查询之前,先来查询看看每个地址的数量 -
sqlite> SELECT address, count(address) as total_number FROM student GROUP BY address ; Beijing|1 Guangzhou|2 Haikou|2 Shanghai|1 Shengzhen|2 Shenzhen|1 sqlite> SELECT address, count(address) as total_number FROM student GROUP BY address HAVING total_number >= 2; Guangzhou|2 Haikou|2 Shengzhen|2 sqlite>