postgresql 想要为has_many关系返回一个JSON数组,怎么做?

tez616oj  于 2022-12-26  发布在  PostgreSQL
关注(0)|答案(1)|浏览(130)

我想我需要一个横向的,一直在看例子,但不能弄清楚...
由于赌场有许多“存款”,我得到多个结果行返回,每个相关的存款一个。
我想只得到1行/每个赌场的结果,然后所有的存款/d.“名称”在json数组格式的一列。

我希望结果如下所示:

Casino.id  |  Casino Name | [{ deposit1 }, {deposit 2}, deposit 3}]  etc...

非:

Casino.id  |  Casino Name | deposit1
Casino.id  |  Casino Name | deposit2
Casino.id  |  Casino Name | deposit3

怎么做

SELECT casino.id
      , casino."name"
      , d."name"
FROM public."Casino" casino

left join "CategoryOnCasinos" coc 
on coc."casinoId" = casino.id 

left join "Category" category 
on category.id = coc."categoryId" 

left join "DepositsOnCasinos" doc 
on doc."casinoId" = casino.id 

left join "Deposit" d 
on d.id = doc."depositId" 

where category.slug = 'all-casinos';
rta7y2nd

rta7y2nd1#

尝试使用JSON_AGG函数。

SELECT casino.id, casino."name", json_agg(d."name") as deposits
FROM public."Casino" casino
LEFT JOIN "CategoryOnCasinos" coc 
ON coc."casinoId" = casino.id 
LEFT JOIN "Category" category 
ON category.id = coc."categoryId" 
LEFT JOIN "DepositsOnCasinos" doc 
ON doc."casinoId" = casino.id 
LEFT JOIN "Deposit" d 
ON d.id = doc."depositId" 
WHERE category.slug = 'all-casinos'
GROUP BY casino.id, casino."name"

这应该为每个赌场返回一行,并在deposit列中返回存款的JSON数组。
ref

相关问题