






















以下为 SQL 中复杂查询的用法解析,聚焦子查询与连接。
学习内容
示例代码与讲解
1. 子查询
SELECT *
FROM products
WHERE unit_price > (
SELECT unit_price
FROM products
WHERE product_id = 3
);
2. IN 运算符
SELECT *
FROM products
WHERE product_id NOT IN (
SELECT DISTINCT product_id
FROM order_items
);
3. 子查询与连接对比
USE sql_invoicing;
SELECT *
FROM clients
WHERE client_id NOT IN (
SELECT DISTINCT client_id
FROM invoices
);
SELECT *
FROM clients
JOIN invoices USING (client_id);
SELECT *
FROM clients
LEFT JOIN invoices USING (client_id)
WHERE invoice_id IS NULL;
4. ALL 关键字
SELECT *
FROM invoices
WHERE invoice_total > (
SELECT MAX(invoice_total)
FROM invoices
WHERE client_id = 3
);
SELECT *
FROM invoices
WHERE invoice_total > ALL (
SELECT invoice_total
FROM invoices
WHERE client_id = 3
);
作业
1. 子查询 - 高薪员工
USE sql_hr;
SELECT first_name, last_name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary) AS AVG_salary
FROM employees
);
2. IN - 无发票客户
USE sql_invoicing;
SELECT *
FROM clients
WHERE client_id NOT IN (
SELECT DISTINCT client_id
FROM invoices
);
3. 子查询与连接 - 订购产品 3 的客户
USE sql_store;
SELECT customer_id, first_name, last_name
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM order_items
JOIN orders USING (order_id)
WHERE product_id = 3
);
SELECT DISTINCT customer_id,
first_name, last_name
FROM customers c
JOIN orders USING (customer_id)
JOIN order_items oi USING (order_id)
WHERE oi.product_id = 3;
总结
本次解析了子查询(比较与 IN)、子查询与连接的对比及 ALL 关键字用法。基于 sql_store、sql_hr 和 sql_invoicing 数据库。后续将探讨更多查询优化技巧。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。