是否可以合并两个简单的数据库查询以获得包含哈希的单个回复
Is it possible to merge two simple DB queries to get a single reply containing a hash
在我的 blog-like 应用中,我有两个单独的查询;
Select id, title, content from posts where id ='$a_post_id'
和
Select tagname, tagscore from tags where postid ='$a_post_id'
由于我的数据库托管在与我的应用程序不同的服务器上,因此我的主要性能问题是两个查询的服务器请求绕行。
我想知道是否可以将两个查询合并为一个查询,以便预期输出为
“$a_post_id”的帖子详细信息= id、标题、内容、标签(标签名称、标签分数的哈希值)
类似于联接但行不对称的东西。或者加入返回的哈希...
此外,这听起来像是解决一个简单问题的好方法,但我是否遗漏了什么?假设此解决方案可行,是否有任何明显的缺点与之相关?
如果 JSON key/value 对没问题,你可以这样:
select p.id, p.title, p.content,
jsonb_object_agg(t.tagname, t.tagscore) as tags
from posts p
left join tags t on t.postid = p.id
where p.id ='$a_post_id'
group by p.id;
以上假设posts.id
定义为主键
在我的 blog-like 应用中,我有两个单独的查询;
Select id, title, content from posts where id ='$a_post_id'
和
Select tagname, tagscore from tags where postid ='$a_post_id'
由于我的数据库托管在与我的应用程序不同的服务器上,因此我的主要性能问题是两个查询的服务器请求绕行。 我想知道是否可以将两个查询合并为一个查询,以便预期输出为
“$a_post_id”的帖子详细信息= id、标题、内容、标签(标签名称、标签分数的哈希值)
类似于联接但行不对称的东西。或者加入返回的哈希...
此外,这听起来像是解决一个简单问题的好方法,但我是否遗漏了什么?假设此解决方案可行,是否有任何明显的缺点与之相关?
如果 JSON key/value 对没问题,你可以这样:
select p.id, p.title, p.content,
jsonb_object_agg(t.tagname, t.tagscore) as tags
from posts p
left join tags t on t.postid = p.id
where p.id ='$a_post_id'
group by p.id;
以上假设posts.id
定义为主键