-- 创建数据库
CREATE DATABASE IF NOT EXISTS `JD`
CHARACTER SET `utf8`
COLLATE `utf8_persian_ci`;
-- 使用
USE JD;
-- 创建表
CREATE TABLE IF NOT EXISTS `JD`.`goods` (
id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL ,
cate_name VARCHAR(40) NOT NULL,
brand_name VARCHAR(40) not null,
price decimal(10,3) NOT NULL DEFAULT 0,
is_show bit NOT NULL DEFAULT 1,
is_saleoff bit NOT NULL DEFAULT 0
) ENGINE = InnoDB CHARSET = utf8 COLLATE utf8_persian_ci;
-- 插入数据
INSERT INTO
`JD`.`goods`
VALUES
(0,"r510vc 15.6英寸笔记本","笔记本","华硕","3399",DEFAULT,DEFAULT);
INSERT INTO
`JD`.`goods`
VALUES
(0,"y400n 14英寸笔记本","笔记本","联想","4999",DEFAULT,DEFAULT);
INSERT INTO
`JD`.`goods`
VALUES
(0,"g150th 15.6英寸笔记本","游戏本","雷神","8499",DEFAULT,DEFAULT);
INSERT INTO
`JD`.`goods`
VALUES
(0,"x550cc 15.6英寸笔记本","笔记本","华硕","2799",DEFAULT,DEFAULT);
INSERT INTO
`JD`.`goods`
VALUES
(0,"svp13226 超极本","超极本","索尼","7999",DEFAULT,DEFAULT);
INSERT INTO
`JD`.`goods`
VALUES
(0,"ipad mini 7.9英寸平板电脑","平板电脑","苹果","1999",DEFAULT,DEFAULT);
INSERT INTO
`JD`.`goods`
VALUES
(0,"ipad air 9.7存平板电脑","平板电脑","苹果","3388",DEFAULT,DEFAULT);
-- 查询类型为 cate_name 为超极本的商品名称 的name,price
select name,price from goods where cate_name="超极本";
-- 显示商品种类
-- 1>分组
select cate_name from goods group by cate_name;
-- 2>DISTINCT
select distinct cate_name from goods;
-- 求所有电脑产品的平均价格 ,并保留两位小数
select round(avg(price),2) from goods where cate_name in ("笔记本","游戏本","超极本","平板电脑");
-- 显示每种类型cate_name的的平均价格
select cate_name,avg(price) from goods GROUP BY cate_name;
-- 查询每种商品的最贵max,最便宜min,平均价avg,数量count
select max(price) from goods;
-- 查询所有大于平均价格的商品,并按照价格降序排序
select * from goods where price > (select avg(price) from goods) ORDER BY price DESC;
-- 查询每种类型中最贵的电脑信息
-- 1.查出每个分类的最贵的
select cate_name,max(price) as max_price from goods GROUP BY cate_name
-- 2.内连接取交集
select * from
goods
inner join
(select cate_name,max(price) as max_price from goods GROUP BY cate_name) as r
on
goods.cate_name=r.cate_name and goods.price=r.max_price;