[英]JdbcTemplate SELECT query to get unique rows (each row with unique ID is present once)
有人願意幫助我完成一個 jdbctemplate 查詢嗎?
只需要獲取具有唯一 ID 但存在重復的行,因為其他列(例如日期)具有不同的值。 我需要最好獲得最大日期,並且結果集不應有任何重復。 :X
select files.id, files.popularity, user_clicked_files.last_clicked from files inner join user_clicked_files on files.id = user_clicked_files.file_id where user_clicked_files.last_clicked > ? order by files.popularity desc limit 10
輸出:
[File [id=1a9227b2-d337-4c4b-a26c-42ed8c94de34, last_clicked='2022-05-30', popularity='8'],
File [id=1a9227b2-d337-4c4b-a26c-42ed8c94de34, last_clicked='2022-06-03', popularity='8'],
File [id=61f3860c-22b3-4c24-90bd-98c7f520fad7, last_clicked='2022-06-04', popularity='8'],
File [id=61f3860c-22b3-4c24-90bd-98c7f520fad7, last_clicked='2022-06-03', popularity='8'],
File [id=d70ff033-04cb-4205-acfe-2432f66525c2, last_clicked='2022-05-30', popularity='7'],
File [id=d70ff033-04cb-4205-acfe-2432f66525c2, last_clicked='2022-05-30', popularity='7'],
File [id=d70ff033-04cb-4205-acfe-2432f66525c2, last_clicked='2022-05-31', popularity='7'],
File [id=9543b842-d592-46df-a63c-8e7c14791169, last_clicked='2022-06-04', popularity='7'],
File [id=d70ff033-04cb-4205-acfe-2432f66525c2, last_clicked='2022-05-29', popularity='7'],
File [id=d70ff033-04cb-4205-acfe-2432f66525c2, last_clicked='2022-06-04', popularity='7']]
這幾乎有效,但不完全有效。 可悲的是有重復。
這是我正在使用的兩張表。
CREATE TABLE files
(
id uuid DEFAULT gen_random_uuid() not null primary key,
file_name VARCHAR(255),
popularity INTEGER
);
CREATE TABLE user_clicked_files
(
user_id uuid,
file_id uuid,
last_clicked date,
PRIMARY KEY (user_id, file_id)
);
PS.:使用 PostgreSQL
您可以使用row_number()over()
窗口函數和下面的公共表表達式來選擇每個 id 最近點擊的行:
with cte as
(
select files.id, files.popularity, user_clicked_files.last_clicked ,ROW_NUMBER()over(partition by files.id order by user_clicked_files.last_clicked desc)rn
from files
inner join user_clicked_files on files.id = user_clicked_files.file_id
where user_clicked_files.last_clicked > ?
)
select id, popularity, last_clicked from cte where rn=1
order by popularity desc limit 10
弄清楚了。 這是查詢。
select f.id, f.popularity, x.last_clicked
from files f
join (
select file_id, max(last_clicked) as last_clicked
from user_clicked_files
where last_clicked > ?
group by file_id) x
on (f.id=x.file_id)
order by f.popularity desc
limit 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.