首页 > 数据库> > |NO.Z.00063|——————————|BigDataEnd|——|Java&MySQL索引/存储过程/触发器.V04|-------------------------|MySQL.v04|使
|NO.Z.00063|——————————|BigDataEnd|——|Java&MySQL索引/存储过程/触发器.V04|-------------------------|MySQL.v04|使
作者:互联网
[BigDataJava:Java&MySQL索引/存储过程/触发器.V04] [BigDataJava.MySQL基础][|章节四|mysql基础|mysql索引/存储过程/触发器|使用视图进行查询操作|]
一、使用视图进行查询操作
### --- 需求: 查询各个分类下的商品平均价格
~~~ # 通过 多表查询
SELECT
cname AS '分类名称',
AVG(p.`price`) AS '平均价格'
FROM products p LEFT JOIN category c ON p.`category_id` = c.`cid`
GROUP BY c.`cname`;
~~~ # 通过视图查询 可以省略连表的操作
SELECT
cname AS '分类名称',
AVG(price) AS '平均价格'
FROM products_category_view GROUP BY cname;
### --- 需求: 查询鞋服分类下最贵的商品的全部信息
~~~ 通过连表查询
~~~ 先求出鞋服分类下的最高商品价格
SELECT
MAX(price) AS maxPrice
FROM
products p LEFT JOIN category c ON p.`category_id` = c.`cid`
WHERE c.`cname` = '鞋服'
### --- 将上面的查询 作为条件使用
SELECT * FROM products p LEFT JOIN category c ON p.`category_id` = c.`cid`
WHERE c.`cname` = '鞋服' AND p.`price` =
(SELECT
MAX(price) AS maxPrice
FROM
products p LEFT JOIN category c ON p.`category_id` = c.`cid`
WHERE c.`cname` = '鞋服');
### --- 通过视图查询
SELECT * FROM products_category_view pcv
WHERE pcv.`cname` = '鞋服'
AND pcv.`price` = (SELECT MAX(price) FROM products_category_view WHERE cname =
'鞋服')
二、sql语句### --- sql语句
~~~ 使用视图进行查询操作
-- 查询各个分类下的商品平均价格
/*
1.查询哪些表 分类表 商品表
2.查询条件是什么 分组操作
3.要查询的字段 平均价格,分类名
4.多表的连接条件 category_id = cid
*/
-- 使用多表方式查询
SELECT
c.`cname`,
AVG(p.`price`)
FROM products p LEFT JOIN category c ON p.`category_id` = c.`cid`
GROUP BY c.`cname`;
-- 通过视图查询
SELECT
pc.`cname`,
AVG(pc.`price`)
FROM products_category_view pc GROUP BY pc.`cname`;
-- 查询鞋服分类下最贵的商品的全部信息
-- 多表查询
-- 1.查询鞋服分类中 最高的商品价格
SELECT
MAX(p.`price`)
FROM products p LEFT JOIN category c ON p.`category_id` = c.`cid`
WHERE c.`cname` = '鞋服';
-- 2.进行子查询 将上面的查询结果作为条件
SELECT
*
FROM products p LEFT JOIN category c
ON p.`category_id` = c.`cid`
WHERE c.`cname` = '鞋服' AND p.`price` =
(
SELECT
MAX(p.`price`)
FROM products p LEFT JOIN category c ON p.`category_id` = c.`cid`
WHERE c.`cname` = '鞋服'
);
-- 通过视图查询
SELECT
*
FROM products_category_view pc
WHERE pc.`cname` = '鞋服' AND pc.`price` =
(
-- 子查询 求出鞋服分类下的最高价格
SELECT MAX(pc.`price`) FROM products_category_view pc
WHERE pc.`cname` = '鞋服' );
===============================END===============================
Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart ——W.S.Landor
来自为知笔记(Wiz)
标签:category,V04,视图,查询,cname,products,鞋服,MySQL,SELECT 来源: https://www.cnblogs.com/yanqivip/p/16102143.html