如何摆脱Postgres查询中继承的SELECT?

时间:2015-12-27 09:35:25

标签: sql postgresql

Postgres 9.4
我想,这样的查询不是数据库性能方面的最佳方法:

error "not implemented"

???包含json对象,其中包含来自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命令 我有请求,它使用多个继承的notification

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

最外层查询仅将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功能。