学习 MySQL,整理语法知识,可以打开左侧的「MySQL基础」专栏查看全系列笔记
子查询
当从多个数据库表查询多种数据时,
通常有以下两种使用途径
1、利用子查询进行过滤
子查询时由内向外处理 SELECT 语句的
子查询通常与 WHERE…IN…一起使用
SELECT cust_name, cust_contact
FROM customers
WHERE cust_id IN (SELECT cust_id
FROM orders
WHERE order_num IN (SELECT order_num
FROM orderitems
WHERE pro_id = '100'));
2、作为计算字段使用子查询
SELECT cust_name,
cust_state,
(SELECT COUNT(*)
FROM orders
WHERE order.cust_id = customers.cust_id) AS orders
FROM customers
ORDER BY cust_name;