gpt4 book ai didi

postgresql - 如何使用 postgres 从子查询中获取行的关联数组

转载 作者:行者123 更新时间:2023-11-29 12:04:34 26 4
gpt4 key购买 nike

我是 postgres 的新手,在我从 mySQL 过渡之前尝试了一些东西。

我想做的是将一组关联数组放入单个查询中。它与可以选择多种联系类型(如电话、电子邮件和 Facebook)的用户有关,我想将它们检索到“联系人”列中。

可视化:

{
"first_name": "This",
"last_name": "is me",
"likes": [],
"city": null

我想得到这样的东西:

{
"first_name": "This",
"last_name": "Is me",
"likes": [],
"city": null,
"contact":
[
{"type":1, "value":"myemail@gmail.com", "privacy_rule":1},
{"type":4, "value":"myfacebook", "privacy_rule":1},
{"type":9, "value":"mylinkedin", "privacy_rule":1}
]
}

所以主要查询是:

SELECT u.first_name, u.last_name, u.about, ARRAY(SELECT like_id FROM users_likes l WHERE l.user_id = u.user_id), u.city FROM users u WHERE user_id = {id}

子查询将是:

SELECT c.type, c.value, c.privacy_rule FROM users_contact c WHERE c.user_id = u.user_id

但是如何将它集成到主查询中以返回结果行数组?有可能吗?

提前致谢!

罗恩

最佳答案

啊,经过更多的填充,这里是答案。使用 json_build_object:

SELECT u.first_name, u.last_name, 
ARRAY(SELECT like_id FROM users_likes l WHERE l.user_id = u.user_id) as likes,
ARRAY(SELECT json_build_object("contact_id", c.contact_id,
"value", c.value, "privacy",c.privacy)
FROM users_contact c WHERE c.user_id = u.user_id) as contact
FROM users_basic u WHERE user_id = {id}

这给出:

"first_name": "This",
"last_name": "Is Me",
"about": null,
"likes": [],
"city": null,
"contact": [
{
"contact_id": 1,
"value": "bbla",
"privacy": 2,
"type": "Phone"
},
{
"contact_id": 3,
"value": "blabla",
"privacy": 2,
"type": "Company Email"
},
{
"contact_id": 4,
"value": "blablabla",
"privacy": 2,
"type": "Telegram Id"
}
]

希望对大家有帮助

关于postgresql - 如何使用 postgres 从子查询中获取行的关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33792235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com