我遇到的问题可以使用类似于SO的系统进行模拟:帖子和标签。为了得到我的帖子,我可能会这样做:
SELECT title, body, author FROM posts WHERE id = ?
然后非常简单地获取我的标签
SELECT tag_id FROM tags_on_posts WHERE post_id = ?
我们说我有一个像SO一样的限制,每个帖子只能有5个标签。无论如何我可以在一个查询中执行此操作吗?
SELECT title, body, author, tag1, tag2, tag3, tag4, tag5
FROM posts
JOIN /*help*/
WHERE id = ?
答案 0 :(得分:2)
您可以将标签聚合为字符串并在应用程序端将其拆分
select
title, body, author,
string_agg(tag_id, ',') as tag_ids
from
posts p
inner join
tags_on_posts top on p.id = top.post_id
where p.id = ?
group by 1, 2, 3
如果标签名称在第三个表中
select
title, body, author,
string_agg(tag_name, ',') as tag_names
from
posts p
inner join
tags_on_posts top on p.id = top.post_id
inner join
tags t on t.id = top.tag_id
where p.id = ?
group by 1, 2, 3