视图和子查询

什么是视图:从SQL角度来看,视图就是一张表
与表的区别是:是否保存了实际的数据

视图的优点:

  1. 无需保存数据,节省储存设备容量。
  2. 将select语句保存成视图,就可以不用每次都从新书写
    注:应将经常使用的select保存成视图
创建视图

创建一个名为商品合计表的视图

CREATE VIEW ProductSum (product_type, cnt_product)
AS
SELECT product_type, COUNT(*)
	FROM Product
 GROUP BY product_type;

创建视图之后可以使用简单的select语句查询。

删除视图

使用DROP VIEW

多重视图

视图之前上再创建视图,ProductSum为之前创建的视图

CREATE VIEW ProductSumJim (product_type, cnt_product)
AS
SELECT product_type, cnt_product
FROM ProductSum
WHERE product_type = '办公用品';	

对多数DBMS来说,多重视图会降低SQL的性能,所以应该尽量避免创建多重视图。

视图的限制
  1. 定义视图不要使用ORDER BY子句,因为视图和表一样数据是没有顺序的
  2. 对视图进行更新,不能使用(INSERT/DELETE/UPDATE)语句
视图更新

有些视图可以跟新,但必须满足,select子句为单表,既没有聚合又没有结合的select语句

CREATE VIEW ProductJim (product_id, product_name, product_type, sale_price, purchase_price, regist_date)
AS 
SELECT *
	FROM Product
 WHERE product_type = '办公用品';
-- 向视图插入数据(原表也插入了此条数据)
INSERT INTO ProductJim VALUES ('0009', '印章', '办公用品', 95, 10, '2009-11-30');
子查询(一次性视图)

执行顺序:内层的select子句——>外层的select子句

SELECT product_type, cnt_product
FROM (SELECT product_type, COUNT(*) AS cnt_product
				FROM Product
			 GROUP BY product_type) AS ProductSum;

注:为子查询设定名称时,需要使用AS关键字,该关键字有时也可以省略。

标量子查询:标量子查询就是返回单一值(一行一列)的子查询
1.在where子句中使用标量子查询

*不能在where子句中使用聚合函数(下面这句是会报错的!!!!)

SELECT * FROM product 
WHERE sale_price > AVG(sale_price);

> 1111 - Invalid use of group function

计算平均销售单价的标量子查询(返回单一结果(一行一列))

 select avg(sale_price) from product;

汇总:where中使用标量子查询

 SELECT * FROM product 
 WHERE sale_price > (select avg(sale_price) from product);

注:标量子查询通常可以在任何使用单一值的位置都可以使用(select/group by/having...)

2.select中使用标量子查询
-- 标量子查询结束作为常数
SELECT product_id, 
	   product_name, 
	   sale_price,
	   (SELECT AVG(sale_price) FROM Product) AS avg_price 
FROM Product;
3.having子句中使用标量子查询
SELECT product_type, AVG(sale_price)
	FROM Product
 GROUP BY product_type
HAVING AVG(sale_price) > (SELECT AVG(sale_price) FROM Product);

关联子查询

在细分的组内进行比较时,需要使用关联子查询

SELECT product_type, product_name, sale_price
	FROM Product AS P1
 WHERE sale_price > (SELECT AVG(sale_price)	
					   FROM Product AS P2 
					 WHERE P1.product_type = P2.product_type ROUP BY product_type);
原文地址:https://www.cnblogs.com/sanzashu/p/11027401.html