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; -
总结