ROW_NUMBER执行内部连接时出现意外结果

时间:2017-07-20 14:53:08

标签: sql postgresql inner-join row-number

我构建了这个SQL请求,

SELECT 
      distinct c_users.id,
      c_photos.user_id,
      c_photos.pic_filename,
      c_users.user_first_name,
      c_users.user_last_name,
      c_users.description,
      c_users.curriculum_diploma_1,
      ROW_NUMBER() OVER(ORDER BY c_users.id ASC) AS rank
FROM
    c_users
INNER JOIN
    c_photos
ON
    c_users.id=c_photos.user_id
WHERE 
    lower(location_town) LIKE '%lille%' 
    AND
    (c_photos.pic_type='profile' OR c_photos.pic_type='photo')    
LIMIT
   9 
;

这是输出,

output

排名栏有一些意想不到的结果,我希望它是1,2,3等,而不是94,84,25等。我无法弄清楚如何做到这一点。

谢谢,

伦纳德

3 个答案:

答案 0 :(得分:1)

如果您想要特定订单的结果,则需要order by。我建议:

order by c_users.id 

order by rank

编辑:

我不确定row_number()如何与distinct一起使用。我对group by感到更舒服。但是,在您的情况下,我怀疑是否需要重复删除(除非用户有两张同名照片)。

SELECT u.id, p.user_id, p.pic_filename, u.user_first_name, u.user_last_name,
       u.description, u.curriculum_diploma_1,
       ROW_NUMBER() OVER (ORDER BY u.id ASC) AS rank
FROM c_users u INNER JOIN
     c_photos p
     ON u.id = p.user_id
WHERE lower(location_town) LIKE '%lille%' AND
      p.pic_type in ('profile', 'photo')
LIMIT 9 ;

您可以添加:

GROUP BY u.id, p.user_id, p.pic_filename, u.user_first_name, u.user_last_name,
         u.description, u.curriculum_diploma_1 

如有必要。

答案 1 :(得分:0)

with CTE as
(
SELECT 
      distinct c_users.id,
      c_photos.user_id,
      c_photos.pic_filename,
      c_users.user_first_name,
      c_users.user_last_name,
      c_users.description,
      c_users.curriculum_diploma_1,
      ROW_NUMBER() OVER(ORDER BY c_users.id ASC) AS rank
FROM
    c_users
INNER JOIN
    c_photos
ON
    c_users.id=c_photos.user_id
WHERE 
    lower(location_town) LIKE '%lille%' 
    AND
    (c_photos.pic_type='profile' OR c_photos.pic_type='photo')    
)
select *
from CTE
where rank <=9

将其打包在CTE /查询中并使用row_number,或者按照新列的顺序排序(根据Gordon的回答),以使限制按预期工作。

答案 2 :(得分:0)

明确的陈述是造成这种情况的。你可以试试这个:

pause