Postgresql 显示日记账分录并与主表联接

Postgresql 显示日记账分录并与主表联接,postgresql,Postgresql,我有一个日志系统,其表结构如下: [journal_logs] id title created_at [journal_entries] id journal_log_id body created_at 所以日志由一个或多个条目组成 在我的网页上,我想列出最近的日志以及条目 例如: "Log 10" "entry 1" "entry 2" "entry 3" "Log 9" "entry 1" "Log 8" "entry 1" "entry 2" 有可能通过一个

我有一个日志系统,其表结构如下:

[journal_logs]
id
title
created_at

[journal_entries]
id
journal_log_id
body
created_at
所以日志由一个或多个条目组成

在我的网页上,我想列出最近的日志以及条目

例如:

"Log 10"
  "entry 1"
  "entry 2"
  "entry 3"

"Log 9"
 "entry 1"

"Log 8"
 "entry 1"
 "entry 2"
有可能通过一个查询生成这样的输出吗?

下面是一个示例

数据样本:

查询示例:

10a1 2. 3. 8a1 2. 9a1
t=# create table journal_logs(id int,title text);
CREATE TABLE
t=# create table journal_entries(id int,journal_log_id int);
CREATE TABLE
t=# insert into journal_logs select 8,'a';
INSERT 0 1
t=# insert into journal_logs select 9,'a';
INSERT 0 1
t=# insert into journal_logs select 10,'a';
INSERT 0 1
t=# insert into journal_entries select 1,8;
INSERT 0 1
t=# insert into journal_entries select 2,8;
INSERT 0 1
t=# insert into journal_entries select 1,9;
INSERT 0 1
t=# insert into journal_entries select 1,10;
INSERT 0 1
t=# insert into journal_entries select 2,10;
INSERT 0 1
t=# insert into journal_entries select 3,10;
INSERT 0 1
t=# with p as (
 select concat('<ul>',l.id,l.title) ul,concat('<li>',e.id) li
 from journal_logs l
 join journal_entries e on l.id = journal_log_id
)
select
 concat(
  case when li = min(li) over (partition by ul order by li) then ul end
 ,concat(li, case when li = max(li) over (partition by ul) then '</ul>' end)) html
from p;
       html
------------------
 <ul>10a<li>1
 <li>2
 <li>3</ul>
 <ul>8a<li>1
 <li>2</ul>
 <ul>9a<li>1</ul>
(6 rows)