Postgres 9.4
我想,就数据库性能而言,这样的查询不是最佳方法:
SELECT t.name,
t.description,
t.rating,
t.readme,
t.id AS userid,
t.notifications
FROM ( SELECT "user".name,
"user".description,
"user".rating,
"user".readme,
"user".id,
( SELECT array_to_json(array_agg(row_to_json(notifications.*))) AS array_to_json
FROM ( SELECT notification.id,
notification.action_type,
notification.user_id,
notification.user_name,
notification.resource_id,
notification.resource_name,
notification.resource_type,
notification.rating,
notification.owner
FROM notification
WHERE (notification.owner = "user".id)
ORDER BY notification.created DESC) notifications) AS notifications
FROM "user") t
notification
列包含 json 对象以及来自 notification
表的所有匹配行。
我应该如何重建此查询以同样的方式接收数据?我想,我应该以某种方式使用 JOIN
命令。
我有一个请求,它利用了多个继承的 SELECT
。
感谢您的宝贵时间!
最佳答案
最外层查询仅将id
别名为userid
。您可以将别名移至内部查询,并完全省略外部查询。
然后您可以创建一个函数来创建通知 JSON:
create or replace function get_user_notifications(user_id bigint)
returns json language sql as
$$
select array_to_json(array_agg(row_to_json(n)))
from (
select id
, action_type
, ... other columns from notification ...
from notification
-- Use function name to refer to parameter not column
where user_id = get_user_notifications.user_id
order by
created desc
) n
$$;
现在您可以将查询写成:
select id as userid
, ... other columns from "user" ...
, get_user_notifications(id) as notifications
from "user" u;
这看起来好多了,代价是必须维护 Postgres 函数。
关于sql - 如何摆脱 Postgres 查询中继承的 SELECT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34479220/