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

标签 sql postgresql

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/

相关文章:

mysql - 从其他两列计算 SQL 中的获胜百分比

sql - SERIALIZABLE 隔离级别上的两个并发事务

mysql - jOOQ如何根据配置来处理多个数据库引擎

postgresql - 无法连接 psql : SSL error: invalid padding

python - SQLAlchemy:组内不同

SQL 查询帮助跨多个表的列的总和

mysql - 我的查询没有使用我的索引,我如何使用解释计划并用 MySQL 修复这个缓慢的查询

SQL 规范化现有(多对多)数据

php - 如何使用使用 `sqliteCreateFunction` 自定义的 LIKE 语句来转义参数化查询中的通配符?

postgresql - Laravel postgresql 不区分大小写