Question

I have a requirement that needs to query top 5 news for each type and return to frontend, implemented by JPA.

I've two solutions now,

  1. One is to manually append union SQL by annotation,
  2. Call a service by different parameter type in loop.

in fact what I want is just like SQL as below

select id, title, content 
from portal p 
where p.type = 'NEWS' 
order by create_date 
limit 5 

union 

select id,title,content, 
from portal p 
where p.type = 'MAG' 
order by create_date 
limit 5

union...

Solution A need to code many SQL statements in JAVA, while solution B is not efficient as types is more than 10.

Is there any other way to query the data? by annotation or postgreSQL function? I'm new to both JPA & Postgres.

Thanks in advance.

Was it helpful?

Solution

You can do this with a single SQL statement. I'm not sure whether you'll be able to avoid a table scan. You might need to include some more columns, depending most likely on whether you need to sort by them.

select * 
from (select 
        id, title, content, 
        row_number() over (partition by type order by create_date asc) row_num
      from portal
     ) as numbered_rows
where row_num <= 5;

One advantage of this kind of SQL statement is that it requires no maintenance. It will continue to work correctly no matter how many different types you add.

Think carefully whether you need the first five (order by create_date ASC) or the latest five (order by create_date DESC).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top