我有4张桌子
用户帐户
user_id | username | password
---------+----------+----------
项目表
project_id | project_name | category_id
------------+------------------------------+-------------
user_projects表(多对多关系)
accounts_projects_id | account_id | project_id
----------------------+------------+------------
project_messages表(项目会有很多消息)
message_id | project_id |message| username
------------+------------+--------+---------
登录时,我正在运行一个查询,在该查询中,我使用以下查询获取用户所属项目的数量以及每个项目的消息
SELECT account.user_id,account.username,
array_agg(json_build_object('message',project_messages.message,'username',project_messages.username)) AS messages,
project.project_name
FROM account
JOIN accounts_projects ON account.user_id = accounts_projects.account_id
JOIN project_messages ON accounts_projects.project_id = project_messages.project_id
JOIN project ON project.project_id = accounts_projects.project_id
WHERE account.username=$1
GROUP BY project.project_name,account.user_id
这给了我以下输出
userid,username, messages (json array object),project_name`
87;"kannaj";"{"{\"message\" : \"saklep\", \"username\" : \"kannaj\"}"}";"Football with Javascript"
87;"kannaj";"{"{\"message\" : \"work\", \"username\" : \"kannaj\"}","{\"message\" : \"you've been down to long in the midnight sea\", \"username\" : \"kannaj\"}","{\"message\" : \"Yeaaaa\", \"username\" : \"house\"}"}";"Machine Learning with Python"
87;"kannaj";"{"{\"message\" : \"holyy DIVVEERRR\", \"username\" : \"kannaj\"}"}";"Beethoven with react"
从project_messages表中检索消息时,有没有办法可以使用LIMIT / OFFSET函数?
答案 0 :(得分:1)
为了使我们的示例更简单,我们假设有两个链接表:
t1(id);
t2(id, t1_id);
查询是
select t1.id, array_agg(t2.id)
from t1 join t2 on (t1.id = t2.t1_id)
group by t1.id;
您可以看到,这是您的大型查询的非常简化的变体。
1)阵列
select t1.id, (array_agg(t2.id order by t2.id desc))[3:5]
from t1 join t2 on (t1.id = t2.t1_id)
group by t1.id;
此查询与原始查询一样,但仅返回数组的3,4和5个元素,等于offset 2 limit 3
。
2)子查询和lateral
select
t1.id,
array_agg(t.x)
from
t1 join lateral
(select t2.id as x from t2 where t1.id = t2.t1_id order by t2.id desc offset 2 limit 3) t on (true)
group by t1.id;
此处lateral
关键字允许使用子查询(from
)中主t1.id
子句中提到的其他表中的字段。