从多个表中选择subict

问题描述 投票:1回答:1

我有这样的数据库结构:

CREATE TABLE person (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER NOT NULL,
    hometown_id INTEGER REFERENCES town(id)
);

CREATE TABLE town (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    population INTEGER NOT NULL
);

我想在选择时获得以下结果:

{
    "name": "<person.name>",
    "age": "<person.age>"
    "hometown": {
        "name": "<tometown.name>",
        "population": "<tometown.population>"
    }
}

我已经在使用psycopg2.extras.DictCursor了,所以我想我需要使用SQL的SELECT AS

这是我尝试过没有resullt的例子,我做了很多类似的微调,所有这些都引发了不同的错误:

SELECT
    person(name, age),
    town(name, population) as town,
FROM person
JOIN town ON town.id = person.hometown_id

有没有办法做到这一点,或者我应该单独选择所有列并在Python中构建dict?

Postgres版本信息:

psql (9.4.6, server 9.5.2)
WARNING: psql major version 9.4, server major version 9.5.
         Some psql features might not work.
python sql python-3.x postgresql psycopg2
1个回答
2
投票

smth喜欢?..

t=# with t as (
select to_json(town),* from town
)
select json_build_object('name',p.name,'age',age,'hometown',to_json) "NameItAsYou Wish"
from person p
join t on t.id=p.hometown_id
;
                                NameItAsYou Wish
--------------------------------------------------------------------------------
 {"name" : "a", "age" : 23, "hometown" : {"id":1,"name":"tn","population":100}}
(1 row)
© www.soinside.com 2019 - 2024. All rights reserved.