这是一个数据库示例
table "Users"
fname | lname | id | email
Joe | smith | 1 | yadda@goo.com
Bob | smith | 2 | bob@goo.com
Jane | smith | 3 | jane@goo.com
table "Awards"
userId | award
1 | bigaward
1 | smallaward
1 | thisaward
2 | thataward
table "Invites"
userId | invited
1 | true
3 | true
基本上,你如何在 PostgreSQL 中编写一个允许你创建这样的东西的查询:
[{
fname:"Joe",
lname:"Smith",
id: 1,
email: "yadda@goo.com",
invited: true,
awards: ["bigaward", "smallaward", "thisaward"]
},
{
fname:"Jane",
lname:"Smith",
id: 3,
email: "jane@goo.com",
invited: true,
awards: []
}]
这就是我想要做的......
SELECT users.fname, users.lname, users.id, users.email, invites.invited, awards.award(needs to be an array)
FROM users
JOIN awards on ....(unknown)
JOIN invites on invites.userid = users.id
WHERE invited = true
上面的数组将是所需的输出,只是想不出一个好的一次性查询。我尝试了 PostgreSQL 文档,但无济于事。我想我可能需要一个 WITH 语句?
在此先感谢 Postgres 大师!
PostgreSQL v. 9.2
RhodiumToad 在 postgresql IRC 上回答:
SELECT users.fname, users.lname, .... array(select awards.award from awards where a.id = user.id) as awards
FROM users
JOIN invites on invites.userid = users.id
WHERE invited = true
array() 然后通过它里面的查询......太棒了!