stringcc

mySQL 第六章

01 复杂子查询 先恢复数据库

image

image

image

更新完记得重启

02 子查询 返回单一具体值,查询的结果作为where后面的筛选条件

exercise

image

先返回平均分

image
平均分作为筛选条件,返回了一个单一的具体的值

image

03 IN 运算符 返回一个列表的值

exercise

image

先找有发票的

image

NOT IN

image

04 子查询 和连接

原则
image

exercise

image

子查询
image

连接
image

有重复项

点击查看代码
SELECT DISTINCT
	c.customer_id,
    c.first_name,
    c.last_name
FROM orders o
JOIN customers c USING (customer_id)
JOIN order_items oi USING (order_Id)
WHERE oi.product_id = 3


	-- WHERE customer_id IN(
-- 			SELECT o.customer_id
-- 			FROM orders o
-- 			JOIN order_items oi USING (order_Id)
-- 			WHERE oi.product_id = 3)



image

05 ALL 运算符

ALL就是每一个的意思,返回一列值

image

另一种方法用max函数,max是返回单一值

image

06 ANY关键字 '= ANY' == 'IN'

使用GROUP BY语句时,SQL会对数据进行分组,并且在每个分组上应用聚合函数

先分组 再聚合

image

image

IN 在里面 等价于 = 任何一个 =ANY

image

image

07 相关子查询,子查询和外查询存在相关性

image

image

image

比如外查询员工的办公室是1,如果子查询的办公室也是1 就计算办公室1的平均值 再将外查询办公室为1 的薪资和这个办公室的avg进行比较

在母查询一次时,子查询将整个列表都查询了一遍

exercise

image

一个顾客会有多张发票

所以不同的发票都是一个人
现在要对每个人的发票金额计算
所以筛选条件是 WHERE client_id= i.client_id

image

image

08 EXISTS运算符 提升效率用 可以降低复杂度

image

image

生成列表太大了

另一种方法就是把发票表和顾客表做连接
数据多的话也会生成很长的列表
影响性能

还有一种方法就是
image

image

image

image

image

image

image

exercise

image

点击查看代码
SELECT *
FROM products P
WHERE NOT EXISTS(
	SELECT product_id
    FROM order_items 
    WHERE product_id = P.product_id
	)

image

09 SELECT 子句中的查询,人类本质复读机

子查询可以直接调用新定义的列
聚合函数处理的是一组行的值,并返回单个值。没有SELECT就没有数据来源,没有数据就不能

exercise

image

报错因为没有goupby

image

点击查看代码
SELECT
	c.client_id,
    name,
    (SELECT SUM(invoice_total)
    FROM invoices
    WHERE client_id = c.client_id) AS total_sales,
   --  (SELECT AVG(invoice_total)
--     FROM invoices
--     WHERE client_id = c.client_id) AS average_sales, 这个avg是平均每张发票的钱,不是平均每个客户的消费,要平均的是发票,有些顾客没有支付完

--     ((SELECT total_sales) - (SELECT average_sales)) AS difference

	(SELECT AVG(invoice_total)
		FROM invoices) AS average_sales,
	(SELECT total_sales - average_sales ) AS difference
FROM clients c

image

10 FROM中的子查询

image

临时表中的数据很有用

image
仅限简单查询 ,可以用VIEW

posted on 2026-11-09 18:36  晓晓言  阅读(9)  评论(0)    收藏  举报

导航