MySQL回顾(二)SQL查询(单表)

create table product(
pid int primary key auto_increment,
pname varchar(20),
price double,
pdate timestamp
);
#自动增长列:auto_increment,要求:1,必须整型(int) 2.必须是主键
insert into product values (null,‘谭妮平’,0.01,null);
insert into product values (null,‘李士雪’,38,null);
insert into product values (null,‘左慈’,-998,null);
insert into product values (null,‘黄迎’,99999,null);
insert into product values (null,‘南国强’,99998,null);
insert into product values (null,‘士兵’,1,null);
insert into product values (null,‘李士兵’,698,null);
insert into product values (null,‘李士兵1’,698,null);

  • #简单查询

    #查询所有商品
    SELECT * from product;
    #查询商品名和商品价格
    SELECT pname,price from product;
    #查询所有商品信息使用表别名(as 可以省略)
    SELECT * from product as p;
    #查询商品名,使用列别名(as 可以省略)
    select pname as name from product;
    #去掉重复值(按照价格)
    SELECT DISTINCT(price) FROM product;
    #将所有的商品的价格+10进行显示
    select pname,price+10 from product;

  • #条件查询
    #查询商品名称为"左慈"的商品信息
    select * from product where pname=‘左慈’;
    #查询价格>60元的所有商品信息 where后条件的写法: >, <, =, >=, <=, <> 注意:<> 等价于 !=
    select * from product where price>60;
    #查询商品名称含有"士"字的商品信息 like 使用占位符_和% _代表一个字符,%代表多个字符
    select * from product where pname like ‘%士%’;
    #查询商品id在(3,6,9)范围内的所有商品信息 in在某个范围中获得值
    select * from product where pid in (3,6,9);
    select * from product where pid = 3 or pid = 6 or pid = 9;
    #查询商品名称含有"士"字并且id为6的商品信息
    select * from product where pname like ‘%士%’ and pid = 6;
    #查询id为2或者6的商品信息
    select * from product where pid = 2 or pid = 6;

  • #排序
    #查询所有的商品,按价格进行排序(升序、降序)
    select * from product order by price asc;
    select * from product order by price desc;
    #查询名称有"士"的商品信息并且按照价格降序排序
    select * from product where pname like ‘%士%’ order by price desc;

  • #聚合函数
    #获得所有商品的价格的总和
    select sum(price) from product;
    #获得所有商品的平均价格
    select AVG(price) from product;
    #获得所有商品的个数
    select COUNT(*) from product;

  • #分组
    #添加分类id
    alter table product add cid varchar(32);
    #初始化数据
    update product set cid=‘1’;
    update product set cid=‘2’ where pid in(5,6,7);
    #根据cid字段分组,分组后统计商品的个数。
    select cid, COUNT() from product GROUP BY cid;
    #根据cid分组,分组统计每组商品的平均价格,并且平均价格大于20000元。 分组后不能用where,分组后带有条件只能使用having
    SELECT cid,avg(price),COUNT(
    ) from product GROUP BY cid HAVING avg(price) > 20000;

  • 总结
    在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值