SQL中where与having的区别

SQL中where与having的区别

SQL中where与having的区别_第1张图片

目录

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.

SQL中where与having的区别_第2张图片

创建表

包含字段:名称、年龄、种族、使用的装备

-- 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的区别

你可能感兴趣的:(mysql,sql,java,数据库,大数据)