[英]How do I get rid of inherited SELECTs in Postgres queries?
PostgreSQL 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功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.