我有一个日志系统,其表结构如下:
[journal_logs]
id
title
created_at
[journal_entries]
id
journal_log_id
body
created_at
所以" journal_log"由一个或多个"条目"。
组成在我的网页上,我想列出最新的日志以及条目。
示例:
"Log 10"
"entry 1"
"entry 2"
"entry 3"
"Log 9"
"entry 1"
"Log 8"
"entry 1"
"entry 2"
是否可以使用单个查询生成这样的输出?
答案 0 :(得分:0)
这是<UL><LI>
数据样本:
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)
<ul>10a<li>1
<li>2
<li>3</ul>
<ul>8a<li>1
<li>2</ul>
<ul>9a<li>1</ul>
&#13;