postgresql中的非重复列

问题描述 投票:0回答:2

我的查询就是这样:

SELECT o.id, o.title, oc.category_id,
(SELECT name from categories c where c.id = oc.category_id)
FROM objects o
LEFT JOIN object_categories oc ON oc.object_id = o.id
WHERE type_id = 17

它像图片一样返回我的表

my table

我想返回非重复的类别名称。谁能帮我吗?

mysql postgresql postgresql-9.6
2个回答
0
投票

对于此数据集,您可以只使用distinct

SELECT DISTINCT
    o.id, 
    o.title, 
    oc.category_id,
    c.name,
    count(*) over(partition by o.id) cnt
FROM objects o
LEFT JOIN object_categories oc ON oc.object_id = o.id
LEFT JOIN categories c ON c.c.id = oc.category_id
WHERE type_id = 17 

请注意,由于我发现它更具可读性,因此将categories上的内联子查询转换为常规join


0
投票

为此,您可以使用DISTINCT ON表达式:https://www.postgresql.org/docs/9.0/sql-select.html#SQL-DISTINCT

© www.soinside.com 2019 - 2024. All rights reserved.