去重和别名as

  1. select * from 表名; - 查询表格中的所有的字段,注意:实际开发中不要使用*,要查询什么字段就写什么字段
  2. 使用*的弊端:会严重的影响查询性能(速度)
  3. select price as 价格,pname 产品名称 from product;
  4. select price 原价,price*0.8 折扣价 from product;
  5. 将字段重命名,as可以省略
  6. select distinct price from product;
  7. distinct用于去重处理

where条件筛选

行筛选DQL:
select * from product where price = 800; - 查询到的是所有价格为800的产品
执行过程:

  1. from product
  2. select * - 结果是所有的商品
  3. where price = 800 - 从查询到的结果中进行筛选where符合的结果
    筛选价格不是800的商品:
    select * from product where price!=800;
    select * from product where price<>800;
    select * from product where not (price = 800);
    
    筛选价格在800-2000之间的商品:
    select * from product where price>=800 and price <= 2000;
    select * from product where price between 800 and 2000;
    
    查询商品价格是200或800之间的所有商品
    select * from product where price=200 or price=800;
    select * from product where price in (200,800);
    in关键字用来选择后面括号中的值 - or一样的
    
    空
    select * from product where price is null;
    select * from product where price is not null;
    组合
    select pid,pname from product where pname like "%x%" and pid >10;
    

    模糊查询:

    select * from product where pname like “%o%”; - 只有有o就筛选出来
    “o%” - o开头;”o%” - 表示一个任意字符
    select * from product where pname like "%o"; - 以o结尾
    select * from product where panme like "__o%";
    

    排序

    通过order by 语句,可以将查询出的结果进行排序,放置在select语句的最后!
    格式:
    select * from 表名 where 条件 order by 排序字段 asc|desc;
  • asc升序(默认)
  • desc降序

desc也可以用于查询表结构 - desc表名

执行过程:**

  1. select * from 表名 - 整张表的数据
  2. wehre 条件 - 从整张表的数据中筛选条件结果
  3. order by 排序字段asc|desc; - 从筛选的结果中去进行排序

    聚合函数

    count() - 统计符合条件的数据的条数
    select count(*) from product where price>=800;
    select count(*) total from product where price>800; - 别名total
    
    sum() - 算术累加
    select sum(price) from product;
    
    max() - 最大值
    min() - 最小值
    select min(price) from product;
    
    avg() - 平均值
    select avg(price) from product;
    
    count(),不统计为null的字段。
    avg()和sum(),如果传入的参数类型不是数字类型(Number),返回0;
    max()和min()传入的值非数字类型时,比较长度。

分组

sql单表查询 - 分组:
分组查询就是指使用group by 语句对查询信息进行分组。
格式: selete 字段1,…from 表名 group by 分组字段 having 分组条件;
分组操作中的having子语句,是用于在分组后对数据进行过滤的,作用类似于where条件。
having和where的区别:

  1. having是在分组后对数据进行过滤
  2. where是分组前对数据进行过滤
  3. having后面可以使用分组函数
  4. where后面不可以使用分组函数

分组通常与聚合结合使用!

--按照不同价格进行分组
select price from product group by price;
--按照类别id分组,查看的是该类名的商品个数,平均价格,类别
select count(*),avg(price),category_id from pruduct group by category_id;

行筛选后再分组:

--对非空类别id分组
--注意:分组的语句要放在where条件语句的后面,因为首先要查询出需要的数据之后才能进行分组
select count(*),avg(price),category_id from product where category_id is not null group by category_id;

先分组后再筛选:

--筛选出平均价格在500以上的商品
select count(*),avg(price),category_id from product group by category_id having avg(price)>=500;

为空返回指定值函数(ifnull())

select name,ifnull(salary,"没有") as salary from users order by salary desc;

如果salary的值为null,显示就返回“没有”(自定义)