2015-11-04 75 views
0

我想爲每個部門抓2個產品。 A department有許多aislesaisle有許多products如何抓取每個部門的2種產品?

爲什麼LATERAL中的LIMIT不起作用?目前,它正在返回更多的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

我希望你需要提及LEFT OUTER JOIN橫向和ON真,這將解決您的問題。

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?

相關問題