2014-03-07 36 views
0

我有一个要求,需要查询每个类型的前5个新闻并返回到前端,由JPA实现。postgreSQL分类限制

我现在已经两种解决方案,

  1. 一是通过注释来手动添加联合SQL,
  2. 呼叫通过循环不同参数类型的服务。

其实我要的是就像SQL如下

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... 

解决方案,需要对代码JAVA许多SQL语句,而溶液B是不是有效,因为类型超过10

有没有其他的方式来查询数据?通过注释或PostgreSQL函数?我是JPA & Postgres的新手。

在此先感谢。

回答

0

您可以使用单个SQL语句执行此操作。我不确定你是否能够避免表扫描。您可能需要包含更多列,具体取决于您是否需要按列排序。

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; 

这种SQL语句的一个优点是它不需要维护。无论您添加多少种不同的类型,它都会继续正常工作。

仔细想想你是否需要前五个(order by create_date ASC)或最近五个(order by create_date DESC)。

+0

是的......我忘了分区。谢谢 :) –