問題:
在僅檢索一個表的同時連接兩個表主表中每條記錄的連接表中的記錄,特別是在連線中存在多個記錄的上下文中
使用子查詢的解決方案:
這種方法有效地避免了從連接表中選擇多個列同時將結果限制為單一記錄時出現的錯誤。關鍵是利用子查詢來檢索所需記錄的主鍵。然後,使用子查詢來篩選主查詢中的聯結表。
SELECT c.id, c.title, p.id AS product_id, p.title AS product_title FROM categories AS c JOIN products AS p ON p.id = ( --- the PRIMARY KEY SELECT p1.id FROM products AS p1 WHERE c.id=p1.category_id ORDER BY p1.id LIMIT 1 )
即使聯結表包含的記錄數量明顯多於主表,此查詢也表現出卓越的效能。
替代方法:
雖然子查詢方法通常是最佳的,但還有其他可用的方法。但是,重要的是要考慮它們潛在的性能影響。
SELECT id, category_title, (array_agg(product_title))[1] FROM (SELECT c.id, c.title AS category_title, p.id AS product_id, p.title AS product_title FROM categories AS c JOIN products AS p ON c.id = p.category_id ORDER BY c.id ASC) AS a GROUP BY id, category_title;
SELECT c.id, c.title, p.id AS product_id, p.title AS product_title FROM categories AS c CROSS JOIN (SELECT product_id, title, ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY id) AS rn FROM products) AS p WHERE rn = 1;
以上是如何在連接表上使用 LIMIT 1 高效連接表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!