我是PostgreSQL的新手。我创建了2个表格:1个用于保存帐户数据的帐户表和1个用于帐单的帐户。
CREATE TABLE account (
id UUID DEFAULT uuid_generate_v1() PRIMARY KEY UNIQUE NOT NULL,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(60) UNIQUE NOT NULL,
password VARCHAR(60) NOT NULL
);
CREATE TABLE posts (
id UUID DEFAULT uuid_generate_v1() PRIMARY KEY UNIQUE NOT NULL,
account_id UUID DEFAULT uuid_generate_v1() REFERENCES account(id),
post TEXT
);
当我尝试在1个查询中获取有关用户帐户+帖子的数据时,我得到了:
[
{
"id": ".....",
"first_name": "Name",
"last_name": "Last Name",
"email": "test@test.com",
"post": "test"
},
{
"id": "......",
"first_name": "Name",
"last_name": "Last Name",
"email": "test@test.com",
"post": "test 1"
}
]
这是我用来获取数据的功能
static get_all_account_data({ id }) {
return new Promise((resolve, reject) => {
pool.query(
`SELECT
account.id,
first_name,
last_name,
email,
post
FROM account INNER JOIN posts
ON posts.account_id = account.id
WHERE account.id=$1
`,
[id],
(e, response) => {
if(e) return reject(e);
resolve(response.rows)
}
)
})
}
这是获取数据的正确方法吗?返回重复的数据似乎是错误的代码?我听说过子查询。我是否需要操纵响应以仅拥有一组帐户数据?
答案 0 :(得分:0)
根据您在上面的评论:
因此,当前的问题将是创建一个函数并返回仅包含一组帐户数据和所有帖子的新obj?
这可以通过Postgresql以多种方式完成。我能想到的一种方法是使用LATERAL JOIN
和aggregate的“帖子”到数组中:
SELECT
account.id,
first_name,
last_name,
email,
jsonb_agg(post) AS posts
FROM
account
LEFT JOIN LATERAL (
SELECT
post
FROM
posts
WHERE
posts.account_id = account.id) post ON TRUE
GROUP BY
account.id