2017-07-20 40 views
0

我建這個SQL請求,意外的結果與ROW_NUMBER做內部聯接

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等。我不知道該怎麼做。

感謝,

倫納德

回答

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 

如果必要的。

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的答案)排序,以便按預期工作。

0

明顯的說法是造成這種情況。你可以試試這個:

SELECT *, ROW_NUMBER() OVER(ORDER BY c_users.id ASC) AS rank from (
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 

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')  
    ) as data 
LIMIT 
    9