我有一个名为deliveries的主表,它与deliveries_languages有一对多关系,如dl,deliveries_markets dm和deliveries_tags dt,其delivery_id为外键。这3个表分别与语言,市场和标签有一对一的关系。另外,交付,表与公司有一对一的关系,并将company_is作为外键。以下是我写的一个查询:
SELECT deliveries.*, languages.display_name, markets.default_name, tags.default_name, companies.name
FROM deliveries
JOIN deliveries_languages dl ON dl.delivery_id = deliveries.id
JOIN deliveries_markets dm ON dm.delivery_id = deliveries.id
JOIN deliveries_tags dt ON dt.delivery_id = deliveries.id
JOIN languages ON languages.id = dl.language_id
JOIN markets ON markets.id = dm.market_id
JOIN tags ON tags.id = dt.tag_id
JOIN companies ON companies.id = deliveries.company_id
WHERE
deliveries.name ILIKE '%new%' AND
deliveries.created_by = '5f331347-fb58-4f63-bcf0-702f132f97c5' AND
deliveries.deleted_at IS NULL
LIMIT 10
这里我得到了冗余的delivery_ids,因为每个delivery_id都有多种语言,市场和标签。我想对不同的delivery_ids使用限制。因此,限制10不应该从上面的连接查询中给出10条记录,而是10条记录中有不同的delivery_id(deliveries.id)。我可能在这里可以使用派生表概念,但我不知道我该怎么做。有人可以帮我解决这个问题。
答案 0 :(得分:0)
在Postgres中,您可以使用distinct on
:
SELECT DISTINCT ON (d.id) d.*, l.display_name, m.default_name, t.default_name, c.name
FROM deliveries d JOIN
deliveries_languages dl
ON dl.delivery_id = d.id JOIN
deliveries_markets dm
ON dm.delivery_id = d.id JOIN
deliveries_tags dt
ON dt.delivery_id = d.id JOIN
languages l
ON l.id = dl.language_id JOIN
markets m
ON m.id = dm.market_id JOIN
tags
ON t.id = dt.tag_id JOIN
companies c
ON c.id = d.company_id
WHERE d.name ILIKE '%new%' AND
d.created_by = '5f331347-fb58-4f63-bcf0-702f132f97c5' AND
d.deleted_at IS NULL
ORDER BY d.id
LIMIT 10;
对于大量数据,这可能效率很低。当像这样使用时,多个连接表产生笛卡尔积。但是,对于少量数据,这应该可以解决您的问题。