我正在尝试执行一个查询,该查询返回一个对象,该对象包含一个列表,该列表已从两个与该对象有很多关系的不同表中合并。
这就是我所做的:
json_agg((select u.name AS name, u.email AS email
from reports wr
LEFT JOIN
reportaccountusers rau
ON rau.reportid = wr.id
LEFT JOIN accountusers au
ON rau.accountuserid = au.id
LEFT JOIN users u
ON au.userid = u.id
where wr.id = 47)
UNION
(select re.email AS name, re.email AS email
from reports wr
LEFT JOIN
reportemails re
ON wr.id = re.reportid
where wr.id = 47)) AS Recipients
但是我做到了,我无法让它真正起作用。
当我这样做时:
select json_agg((select u.name AS name, u.email AS email
from reports wr
LEFT JOIN
reportaccountusers rau
ON rau.reportid = wr.id
LEFT JOIN accountusers au
ON rau.accountuserid = au.id
LEFT JOIN users u
ON au.userid = u.id
where wr.id = 47)
UNION
(select re.email AS name, re.email AS email
from reports wr
LEFT JOIN
reportemails re
ON wr.id = re.reportid
where wr.id = 47)) AS Recipients
我收到错误:
错误:“UNION”处或附近的语法错误 第11行:UNION ^ **********错误**********
错误:“UNION”处或附近的语法错误 SQL状态:42601 性格:283
像这样:
select json_agg(x) from((select u.name AS name, u.email AS email
from reports wr
LEFT JOIN
reportaccountusers rau
ON rau.reportid = wr.id
LEFT JOIN accountusers au
ON rau.accountuserid = au.id
LEFT JOIN users u
ON au.userid = u.id
where wr.id = 47)
UNION
(select re.email AS name, re.email AS email
from reports wr
LEFT JOIN
reportemails re
ON wr.id = re.reportid
where wr.id = 47))x) AS items