Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 如何为每个部门获取2种产品?_Postgresql - Fatal编程技术网

Postgresql 如何为每个部门获取2种产品?

Postgresql 如何为每个部门获取2种产品?,postgresql,Postgresql,我试图为每个部门购买2种产品。一个部门有许多走道,走道有许多产品 为什么横向中的限制不起作用?目前,它正在退回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.depa

我试图为每个部门购买2种产品。一个
部门
有许多
走道
走道
有许多
产品

为什么
横向
中的
限制不起作用?目前,它正在退回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

我希望你需要提到左外连接和右外连接,这将解决你的问题

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);
更多信息请点击此处