我想为每个部门抓2个产品。 department
有很多aisles
,aisle
有很多products
。
为什么LIMIT
中的LATERAL
无效?目前,它正在返回更多的2种产品。
我有:
SELECT d.id, p.* FROM departments d
JOIN aisles a ON d.id = a.department_id, LATERAL (
SELECT * FROM products p1 WHERE p1.aisle_id = a.id ORDER BY p1.id ASC LIMIT 2
) p
WHERE a.department_id IN (3,5);
返回:
id | id | aisle_id | name | image_filename | created_at | updated_at
----+-----+-----------+-----------------------------+-----------------+----------------------------+----------------------------
3 | 149 | 11 | Sleek Wool Watch | foo.png | 2015-10-30 10:03:21.107873 | 2015-10-30 10:03:21.107873
3 | 3 | 12 | Heavy Duty Granite Lamp | foo.png | 2015-10-30 10:03:20.637513 | 2015-10-30 10:03:20.637513
3 | 88 | 12 | Rustic Marble Shirt | foo.png | 2015-10-30 10:03:20.883394 | 2015-10-30 10:03:20.883394
3 | 56 | 13 | Enormous Linen Bottle | foo.png | 2015-10-30 10:03:20.786546 | 2015-10-30 10:03:20.786546
5 | 22 | 24 | Gorgeous Linen Clock | foo.png | 2015-10-30 10:03:20.687868 | 2015-10-30 10:03:20.687868
5 | 104 | 24 | Synergistic Leather Bag | foo.png | 2015-10-30 10:03:20.933504 | 2015-10-30 10:03:20.933504
5 | 80 | 25 | Enormous Leather Bag | foo.png | 2015-10-30 10:03:20.860636 | 2015-10-30 10:03:20.860636
5 | 117 | 25 | Aerodynamic Bronze Gloves | foo.png | 2015-10-30 10:03:21.015299 | 2015-10-30 10:03:21.015299
答案 0 :(得分:0)
我希望您需要提及LEFT OUTER JOIN LATERAL和ON True,这将解决您的问题。
SELECT d.id, p.* FROM departments d
JOIN aisles a ON d.id = a.department_id LEFT OUTER JOIN LATERAL (
SELECT * FROM products p1 WHERE p1.aisle_id = a.id ORDER BY p1.id ASC LIMIT 2
) p
ON True
WHERE a.department_id IN (3,5);
此处提供更多信息 What is the difference between LATERAL and a subquery in PostgreSQL?