任何人都可以帮我查询postgres中的多对多关系表吗?
我有桌子:
> 1.exercise(id,name)
> 2.tag(id,label)
> 3.tag_in_exercise(id,exercise_id,tag_id)
比方说,我们通过tag_in_exercise
将一个练习与两个标签结合在一起使用查询时:
select e.id,t.label from exercise e
left join tag_in_exercise te on e.id=te.exercise_id
left join tag t on te.tag_id=t.id
我会收到json
[ { id: 1,
label: 'basic1' },
{ id: 1,
label: 'basic2' }]
但我希望以嵌套的json
接收它[ { id: 1,
tags:[ {'basic1'},{'basic2'} ]
}]
是否可以通过使用标准的postgresql查询来获取它,或者我需要使用一些ORM?
或者如果存在另一种解决方案,请告诉我,
感谢
答案 0 :(得分:1)
PostgreSQL不会返回您发布的JavaScript对象。您的节点驱动程序正在转换PostgreSQL返回的数组数组,驱动程序将转换为JavaScript对象。
但是,你可以让PostgreSQL返回一个结构,我怀疑你可以使用array_agg转换你想要的结构。
试试这个:
SELECT e.id,array_agg(t.label) AS label
FROM exercise e
LEFT JOIN tag_in_exercise te on e.id=te.exercise_id
LEFT JOIN tag t on te.tag_id=t.id
GROUP BY e.id;
您将获得所需结构的原始PostgreSQL结果,希望驱动程序可以按照您的意图进行翻译:
id | label
----+-----------------
1 | {basic1,basic2}
2 | {NULL}