PostgreSQL:如何仅从 SELECT 中获取第一个结果

时间:2021-06-08 21:05:09

标签: sql postgresql

在我的数据库中,我有两列,products 和 products_photos,其中产品可以有很多 products_photos。我想要做的是一个返回产品但只有一张照片的查询。 我设法编写了这样的查询:

SELECT products.*, file
FROM products, products_photos
WHERE products.id = products_photos.product_id
ORDER BY products.id

但是,由于照片的原因,这仍然会多次返回相同的产品。 我已经尝试使用 DISTINCT 和 LIMIT 但无法正常工作。

2 个答案:

答案 0 :(得分:2)

首先,学习使用正确、明确、标准、可读的 JOIN 语法。 切勿FROM 子句中使用逗号。

其次,Postgres 有一个非常方便的扩展,DISTINCT ON,可以满足您的需求:

SELECT DISTINCT ON (p.id) p.*, pp.file
FROM products JOIN
     products_photos pp
     ON p.id = pp.product_id
ORDER BY p.id

答案 1 :(得分:0)

你也可以使用:

SELECT products.*, file
FROM products, products_photos
WHERE products.id = products_photos.product_id
group by 1,2
order by  products.id
相关问题