问题:
在仅检索一个表的同时连接两个表主表中每条记录的连接表中的记录,特别是在连接表中存在多个记录的情况下。
使用子查询的解决方案:
这种方法有效地避免了从连接表中选择多列同时将结果限制为单个记录时出现的错误。关键是利用子查询来检索所需记录的主键。然后,使用子查询来过滤主查询中的联接表。
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中文网其他相关文章!