在 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 中的一些應用場景,實際上子查詢可以應用于更復雜的查詢和操作。在使用子查詢時,需要注意性能優化和查詢效率,以確保查詢能夠高效地執行。