在SQL查询中*排序后*删除重复项

时间:2018-09-07 08:52:19

标签: sql postgresql duplicates distinct

我有以下SQL查询:

select 
    id,
    name
from
    project
    inner join job on project.id = job.project_id
where
    job.user_id = 'me'
order by
    project.modified desc
limit 10

想法是为给定用户获取有关10个最近使用的项目的信息。

问题是,在多个作业具有相同项目的情况下,这可能返回重复项。除了要重复之外,我还想按modified desc对所有行进行排序,根据idname删除重复项,然后将它们限制为10。

我无法弄清楚该如何实现。谁能指出我正确的方向?

4 个答案:

答案 0 :(得分:1)

由于加入,您得到了重复项。因为您只希望项目表中的列(我假设idname来自该表),所以首先不创建重复项比在联接后删除它们会更好:

select p.id,
       p.name
from project p
where exists (select *
              from job job
              where job.project_id = p.id
                and job.user_id = 'me')
order by p.modified desc
limit 10

答案 1 :(得分:0)

使用row_number尝试此操作-它将在postgresql上工作

select * from 
(select 
    id,
    name,row_number() over(partition by id,name order by modified desc) as rn
from
    project inner join job on project.id = job.project_id
where
    job.user_id = 'me')a where rn=1 order by modified desc limit 10

答案 2 :(得分:0)

您尝试了 SELECT DISTINCT 吗?

select distinct
    id,
    name
from
    project
    inner join job on project.id = job.project_id
where
    job.user_id = 'me'
order by
    project.modified desc
limit 10

答案 3 :(得分:0)

我最终得到了以下结果,似乎工作正常:

select
    p.id,
    p.name
from
    project p
    inner join
    (
        select
            j.id,
            max(j.modified) as max_modified
        from
            job j
        where
            t.user_id = 'me'
        group by
            j.id
        order by
            max_modified desc
        limit 10
    ) ids on p.id = ids.id
order by
    max_modified desc