JdbcTemplate SELECT查询获取唯一行(具有唯一ID的每一行出现一次)



谁愿意帮助我一个jdbctemplate查询?

只需要获取具有唯一id但有重复的行,因为其他列(如date)有不同的值。我需要得到最好的最大日期和结果集不应该有任何重复。: 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)
);

p。:使用PostgreSQL

明白了。这是查询。

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

您可以使用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

相关内容

  • 没有找到相关文章