在 SQL 中,子查询(Subquery)是指嵌套在主查询中的查询语句。子查询可以用于多种应用场景,以下是一些常见的例子:
SELECT * FROM products WHERE price > (SELECT AVG(price) FROM products);
SELECT * FROM orders WHERE customer_id = (SELECT id FROM customers WHERE name = 'John Doe');
SELECT * FROM products WHERE sales = (SELECT MAX(sales) FROM products);
SELECT * FROM products ORDER BY sales DESC LIMIT 3;
SELECT category, AVG(price) as avg_price FROM products GROUP BY category;
SELECT * FROM customers WHERE EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.id);
这些只是子查询在 SQL 中的一些应用场景,实际上子查询可以应用于更复杂的查询和操作。在使用子查询时,需要注意性能优化和查询效率,以确保查询能够高效地执行。