如何加入 2 tables 并在 PostgreSQL 的第一个值中嵌套其他 table 的值列表?
How to join 2 tables and have a list of other table's values nested in the first one in PostgreSQL?
假设我们有这 2 table:人和车
CREATE TABLE person (
id BIGSERIAL NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL
);
CREATE TABLE car (
id BIGSERIAL NOT NULL PRIMARY KEY,
make VARCHAR NOT NULL,
person_id BIGINT NOT NULL REFERENCES person(id)
);
我尝试做的是找到所有人,找到每辆车并创建一个像这样的对象数组
[
{
"id": "PERSON_ID",
"name": "PERSON_NAME",
"cars": [
{
"id": "CAR_ID",
"model": "MODEL_NAME",
"person_id": "PERSON_ID"
}
]
}
]
我尝试在 car
table person
table 上使用带有 JOIN
的 AS
别名,但没有成功工作。有没有办法做到这一点?谢谢!
如果你想在 Postgres 中将结果集作为 array,你可以使用:
select p.*, array_agg(c)
from person p join
car c
on c.person_id = p.id
group by p.id;
如果您还想返回 JSON,可以做类似的事情。
您可以尝试以下方法。查看工作 fiddle:
模式(PostgreSQL v13)
CREATE TABLE person (
id BIGSERIAL NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL
);
CREATE TABLE car (
id BIGSERIAL NOT NULL PRIMARY KEY,
make VARCHAR NOT NULL,
person_id BIGINT NOT NULL REFERENCES person(id)
);
insert into person(name) values ('tom'),('harry');
insert into car (id,make,person_id) values (1,'ford',1),(2,'audi',1),(3,'nissan',2);
查询#1
SELECT
p.id,
p.name,
array_agg(row_to_json(c)) cars
FROM
person p
INNER JOIN
(SELECT id, make model, person_id FROM car) c ON p.id = c.person_id
GROUP BY
p.id,
p.name;
id
name
cars
1
tom
[{"id":1,"model":"ford","person_id":1},{"id":2,"model":"audi","person_id":1}]
2
harry
[{"id":3,"model":"nissan","person_id":2}]
假设我们有这 2 table:人和车
CREATE TABLE person (
id BIGSERIAL NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL
);
CREATE TABLE car (
id BIGSERIAL NOT NULL PRIMARY KEY,
make VARCHAR NOT NULL,
person_id BIGINT NOT NULL REFERENCES person(id)
);
我尝试做的是找到所有人,找到每辆车并创建一个像这样的对象数组
[
{
"id": "PERSON_ID",
"name": "PERSON_NAME",
"cars": [
{
"id": "CAR_ID",
"model": "MODEL_NAME",
"person_id": "PERSON_ID"
}
]
}
]
我尝试在 car
table person
table 上使用带有 JOIN
的 AS
别名,但没有成功工作。有没有办法做到这一点?谢谢!
如果你想在 Postgres 中将结果集作为 array,你可以使用:
select p.*, array_agg(c)
from person p join
car c
on c.person_id = p.id
group by p.id;
如果您还想返回 JSON,可以做类似的事情。
您可以尝试以下方法。查看工作 fiddle:
模式(PostgreSQL v13)
CREATE TABLE person (
id BIGSERIAL NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL
);
CREATE TABLE car (
id BIGSERIAL NOT NULL PRIMARY KEY,
make VARCHAR NOT NULL,
person_id BIGINT NOT NULL REFERENCES person(id)
);
insert into person(name) values ('tom'),('harry');
insert into car (id,make,person_id) values (1,'ford',1),(2,'audi',1),(3,'nissan',2);
查询#1
SELECT
p.id,
p.name,
array_agg(row_to_json(c)) cars
FROM
person p
INNER JOIN
(SELECT id, make model, person_id FROM car) c ON p.id = c.person_id
GROUP BY
p.id,
p.name;
id | name | cars |
---|---|---|
1 | tom | [{"id":1,"model":"ford","person_id":1},{"id":2,"model":"audi","person_id":1}] |
2 | harry | [{"id":3,"model":"nissan","person_id":2}] |