select name,price from goods where cate_name="超级本";--显示商品的种类select cate_name from goods groupby cate_name;--求所有电脑产品的平均价格,并且保留两位小数select round(avg(price),2) as avg_price from goods;--显示每种商品的平均价格select cate_name,round(avg(price),2) as avg_price from goods groupby cate_name;--查询每种类型的商品中 最贵、最便宜、平均价、数量select cate_name,max(price) from goods groupby cate_name;select cate_name,min(price) from goods groupby cate_name;select cate_name,avg(price) from goods groupby cate_name;select cate_name,count(*) from goods groupby cate_name;select cate_name,group_concat(name) from goods groupby cate_name;--查询所有价格大于平均价格的商品,并且按价格降序排序select * from goods where price>(selectavg(price) from goods) orderby price desc;--查询每种类型中最贵的电脑信息selectmax(price) from goods;select * from goods groupby cate_name;select id,name,new_goods.cate_name,new_goods.max_price,price from goods innerjoin (select cate_name,max(price) as max_price from goods groupby cate_name) as new_goods on goods.cate_name= new_goods.cate_name where goods.price=new_goods.max_price;
创建 “商品分类” 表
createtableifnotexists goods_cates(
id int unsigned primarykey auto_increment,
name varchar(50) notnull
);
查询goods表中商品的种类
select cate_name from goods;select cate_name from goods groupby cate_name
将分组结果写入到goods_cates数据表
insertinto goods_cates(name) (select cate_name from goods groupby cate_name);
通过goods_cates数据表来更新goods表
select * from goods as g innerjoin goods_cates as gc on g.cate_name=gc.name;update (goods as g innerjoin goods_cates as gc on g.cate_name=gc.name) set g.cate_name=gc.id;
更新goods表的cate_name字段为cate_name_id
altertable goods change cate_name cate_name_id int unsigned notnull;
通过create…select来创建”商品品牌表”并且同时写入记录,一步到位
createtable goods_brands(
id int unsigned primarykey auto_increment,
name varchar(40) notnull) select brand_name as name from goods groupby brand_name;
通过goods_brands数据表来更新goods数据表
select * from goods as g innerjoin goods_brands as gb on g.brand_name=gb.name;update goods as g innerjoin goods_brands as gb on g.brand_name=gb.name set g.brand_name=gb.id;
更新goods表的brand_name字段为brand_name_id
altertable goods change brand_name brand_name_id int unsigned notnull;
insertinto goods (name,cate_name_id,brand_name_id,price) values('LaserJet Pro P1606dn 黑白激光打印机', 12, 4,'1849');insertinto goods values(0,'LaserJet Pro P8888c 彩色激光打印机', 12, 4,'4998',default,default);
查询所有商品的详细信息 (通过内连接)
select g.id,g.name,c.name,b.name,g.price from goods as g
innerjoin goods_cates as c on g.cate_name_id=c.id
innerjoin goods_brands as b on g.brand_name_id=b.id;
查询所有商品的详细信息 (通过左连接)
select g.id,g.name,c.name,b.name,g.price from goods as g
leftjoin goods_cates as c on g.cate_name_id=c.id
leftjoin goods_brands as b on g.brand_name_id=b.id;