SQL中where与having的区别
Posted Data+Science+Insight
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL中where与having的区别相关的知识,希望对你有一定的参考价值。
SQL中where与having的区别
目录
# WHERE是在聚合之前进行数据行的过滤而HAVING实在聚合之后进行新数据的过滤;
即在SQL语法中WHERE语法的执行早于GROUP BY,而GOUP BY 早于HAVING的执行;
# WHERE
filters rows before grouping (i.e. GROUP BY
) while HAVING
filters rows after grouping.
创建表
包含字段:名称、年龄、种族、使用的装备
-- Create table called adventurers
CREATE TABLE adventurers (
-- string variable
name varchar(255),
-- integer variable
age int,
-- string variable
race varchar(255),
-- string variable
weapon varchar(255)
)
插入数据
在表中插入四条数据
-- Insert into the table adventurers
INSERT INTO adventurers (name, age, race, weapon)
VALUES ('Fjoak Doom-Wife', 28, 'Human', 'Axe'),
('Alooneric Cortte', 29, 'Human', 'Bow'),
('Piperel Ramsay', 35, 'Elf', 'Axe'),
('Casimir Yardley', 14, 'Elf', 'Bow')
进行聚合操作
使用where筛选年龄大约15岁的角色
-- Retrieve the race and average age from the table
SELECT race, AVG(age) FROM adventurers
-- Grouped by race
GROUP BY race
-- That are older than 15
WHERE age > 15
使用having,在聚合后的结果中选取年龄大约20的结果;
-- Retrieve the race and average age from the table
SELECT race, age, AVG(age) FROM adventurers
-- Grouped by race
GROUP BY race age
-- That are older than 20
HAVING age > 20
参考:Group Rows With Conditions
参考:SQL
参考:SQL中where与having的区别
以上是关于SQL中where与having的区别的主要内容,如果未能解决你的问题,请参考以下文章