MySQL子查詢是一種強大的數據過濾工具,它允許你在一個查詢中嵌套另一個查詢。子查詢可以用于過濾、排序和分組等操作。以下是一些使用MySQL子查詢的數據過濾技巧:
SELECT * FROM orders
WHERE customer_id IN (SELECT customer_id FROM customers WHERE country = 'USA');
這個查詢會返回所有位于美國的客戶的訂單。
SELECT * FROM products
WHERE category_id NOT IN (SELECT category_id FROM categories WHERE name = 'Electronics');
這個查詢會返回所有不屬于電子產品類別的產品。
SELECT * FROM employees
WHERE EXISTS (SELECT 1 FROM departments WHERE employees.department_id = departments.id);
這個查詢會返回所有與部門關聯的員工。
SELECT * FROM employees
WHERE NOT EXISTS (SELECT 1 FROM departments WHERE employees.department_id = departments.id);
這個查詢會返回所有沒有與部門關聯的員工。
SELECT * FROM products
ORDER BY (SELECT COUNT(*) FROM sales WHERE products.id = sales.product_id) DESC;
這個查詢會按照產品銷售數量降序排列。
SELECT c.name, COUNT(o.id) as order_count
FROM customers c
JOIN orders o ON c.id = o.customer_id
GROUP BY c.id
HAVING order_count > (SELECT AVG(order_count) FROM (SELECT COUNT(o.id) as order_count FROM customers c JOIN orders o ON c.id = o.customer_id GROUP BY c.id) as subquery);
這個查詢會返回訂單數量高于平均值的客戶及其訂單數量。
UPDATE products
SET price = price * 1.1
WHERE id IN (SELECT product_id FROM sales WHERE quantity > 10);
這個查詢會將銷售數量超過10的產品價格提高10%。
DELETE FROM products
WHERE id NOT IN (SELECT product_id FROM sales);
這個查詢會刪除沒有銷售記錄的產品。
總之,MySQL子查詢提供了強大的數據過濾功能,可以幫助你更有效地處理復雜的數據查詢需求。在使用子查詢時,請注意優化查詢性能,避免出現性能瓶頸。