我有一个名为借项的表,其中包含许多字段,例如(id,名称,描述等)。在该表中,我有一列,其类型为JSON(TermsMessage)(JSON数组),何时我进行选择查询,返回错误
我的查询
`
select
z.loan_id,
z.loan_name,
z.max_amount,
z.min_amount,
z.min_age,
z.max_age,
z.min_loan_term,
z.max_loan_term,
z.TermsMessage,
to_json(array_agg(distinct z.jsjs)) as aims,
to_json(array_agg(distinct z.jsjs1)) as cities,
from(
select
c.loan_id,
c.loan_name,
c.max_amount,
c.min_amount,
c.min_age,
c.max_age,
c.min_loan_term,
c.max_loan_term,
c.TermsMessage,
( select x from (select c.aim_id, c.aim_name) x) as jsjs,
( select x from (select c.city_id, c.city_name) x) as jsjs1
from
( select
l.id as loan_id,
l.name as loan_name,
l.max_amount,
l.min_amount,
l.min_age,
l.max_age,
l.min_loan_term,
l.max_loan_term,
l.TermsMessage,
--
a.id as aim_id,
a.name as aim_name,
--
c.id as city_id,
c.name as city_name
--
from loans as l
left join loan_aims as la on la._loan = l.id
left join aims as a on a.id = la._aim
------------
left join loan_cities as lc on lc._loan=l.id
left join cities as c on c.id = lc._city
------------
) c
) z
group by z.loan_id,
z.loan_name,
z.max_amount,
z.min_amount,
z.min_age,
z.max_age,
z.min_loan_term,
z.max_loan_term;
`
termsMessage必须出现在GROUP BY子句中或在聚合函数中使用
当我将JSON列添加到GROUP BY时,它返回另一个错误
group by z.loan_id,
z.loan_name,
z.max_amount,
z.min_amount,
z.min_age,
z.max_age,
z.min_loan_term,
z.max_loan_term,
z.TermsMessage;
无法识别json类型的相等运算符
答案 0 :(得分:1)
对于数据类型JSON或JSON数组,PostgreSQL没有内置的相等运算符。在按JSON字段分组时,数据库需要知道哪些是相同的值并且可以分组在一起。您可以使用:: jsonb []或:: text []将JSON(或JSON数组)转换为文本数组或JSONb数组来解决此问题。我可能会在查询的最内部进行操作,以使其自然地流过以后:
select
z.loan_id,
z.loan_name,
z.max_amount,
z.min_amount,
z.min_age,
z.max_age,
z.min_loan_term,
z.max_loan_term,
z.TermsMessage,
to_json(array_agg(distinct z.jsjs)) as aims,
to_json(array_agg(distinct z.jsjs1)) as cities,
from(
select
c.loan_id,
c.loan_name,
c.max_amount,
c.min_amount,
c.min_age,
c.max_age,
c.min_loan_term,
c.max_loan_term,
c.TermsMessage,
( select x from (select c.aim_id, c.aim_name) x) as jsjs,
( select x from (select c.city_id, c.city_name) x) as jsjs1
from
( select
l.id as loan_id,
l.name as loan_name,
l.max_amount,
l.min_amount,
l.min_age,
l.max_age,
l.min_loan_term,
l.max_loan_term,
l.TermsMessage::jsonb[] as TermsMessage ,
--
a.id as aim_id,
a.name as aim_name,
--
c.id as city_id,
c.name as city_name
--
from loans as l
left join loan_aims as la on la._loan = l.id
left join aims as a on a.id = la._aim
------------
left join loan_cities as lc on lc._loan=l.id
left join cities as c on c.id = lc._city
------------
) c
) z
group by z.loan_id,
z.loan_name,
z.max_amount,
z.min_amount,
z.min_age,
z.max_age,
z.min_loan_term,
z.max_loan_term,
z.TermsMessage;