在復雜查詢中,內連接(INNER JOIN)是一種常用的連接方式,它可以將兩個或多個表中的數據根據指定的條件進行關聯。以下是一些在復雜查詢中使用內連接的技巧:
SELECT a.id, a.name, b.price
FROM products AS a
INNER JOIN prices AS b ON a.id = b.product_id;
SELECT a.id, a.name, b.price, c.category_name
FROM products AS a
INNER JOIN prices AS b ON a.id = b.product_id
INNER JOIN categories AS c ON a.category_id = c.id;
SELECT a.id, a.name, b.price
FROM (
SELECT id, name, category_id
FROM products
WHERE category_id IN (1, 2, 3)
) AS a
INNER JOIN prices AS b ON a.id = b.product_id;
SELECT a.category_id, c.category_name, COUNT(a.id) AS product_count, SUM(b.price) AS total_price
FROM products AS a
INNER JOIN prices AS b ON a.id = b.product_id
INNER JOIN categories AS c ON a.category_id = c.id
GROUP BY a.category_id;
SELECT a.category_id, c.category_name, COUNT(a.id) AS product_count, SUM(b.price) AS total_price
FROM products AS a
INNER JOIN prices AS b ON a.id = b.product_id
INNER JOIN categories AS c ON a.category_id = c.id
GROUP BY a.category_id
HAVING product_count > 10 AND total_price > 1000;
總之,在復雜查詢中,內連接可以幫助你根據特定條件關聯多個表的數據。通過使用表別名、多個內連接、子查詢、聚合函數和HAVING子句等技巧,可以更有效地處理復雜查詢。