Return 多行只有一个数据

Return only one data from multiple row

我有 4 个 table 称为订单、order_details、产品和存储。每个产品都可以有多个缩略图图像保存在存储空间 table。

我想 return 通过 id return 多行 order_details 的特定订单,其中每个 order_details 只有一个产品。在每个产品中,我只想从存储 table.

中获取一张缩略图

如果我想得到一行 order_id = 1,

SELECT * 
FROM orders o
JOIN order_details od ON o.id = od.order_id
JOIN products p ON p.id = od.product_id 
JOIN storages s ON s.product_id = p.id --> i haven't figured out how to return only one image for every product in order_details
WHERE o.id = 1

有人可以帮我吗,我已经想了好几天了,但还是没弄明白:(

提前致谢。

一个简单的方法是使用row_number():

SELECT *
FROM orders o JOIN
     order_details od
     ON o.id = od.order_id JOIN
     products p
     ON p.id = od.product_id JOIN
     (SELECT s.*,
             ROW_NUMBER() OVER (PARTITION BY product_id ORDER by random()) as seqnum
      FROM storages s
     ) s
     ON s.product_id = p.id
WHERE o.id = 1 AND seqnum = 1;

这 returns 一张随机图片。您可以替换 ORDER BY 以获得您想要的任何图像——最旧的、最新的、最大的、最小的或其他任何图像。

I haven't figured out how to return only one image for every product in order_details

在 Postgres 中,我会推荐 distinct on:

select distinct on (o.id, od.product_id) *
from orders o
join order_details od on o.id = od.order_id
join products p on p.id = od.product_id
join storages s on s.product_id = p.id 
order by o.id, od.product_id, s.id

这保证每个订单和产品只有一行,存储空间最小 id。如果愿意,您可以使用 where 子句过滤给定的订单 ID。

或者您可能想使用订单详细信息的主键而不是产品(这允许在同一订单的两个不同订单详细信息中出现两次相同的产品)。

select distinct on (o.id, od.id) *
from orders o
join order_details od on o.id = od.order_id
join products p on p.id = od.product_id
join storages s on s.product_id = p.id 
order by o.id, od.id, s.id