从多个表中选择subict

时间:2017-02-28 09:22:44

标签: python sql python-3.x postgresql psycopg2

我有这样的数据库结构:

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.

1 个答案:

答案 0 :(得分:2)

是什么样的?..

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)