【发布时间】:2016-10-06 11:08:44
【问题描述】:
我使用pg-promise 库和bluebird 进行相关查询。
我有两张表,a 和 b,看起来像这样:
| a | | b |
|-------| |-------|
| a_id | | b_id |
| prop1 | | prop2 |
| b_a |
其中b.b_a 是对a.a_id 的引用。我想选择与给定prop1 匹配的所有条目,结果应包含所有匹配的a-rows 以及每个a 对应的b-rows。这应该可以通过两个相关查询来实现。两个查询都可能返回多个结果。
如果表 a 只返回一行,我可以这样做:
function getResult(prop1) {
return db.task(function (t) {
return t.one("select * from a where prop1=$1", prop1)
.then(function (a) {
return t.batch([a, t.any("select * from b where b_a=$1", a.a_id)]);
})
.then(function (data) {
var a = data[0];
var bs = data[1];
bs.forEach(function (b) {
b.a = a;
});
return bs;
});
});
}
我还能够为多个 a-results 获取所有匹配的 b-entries,如下所示:
function getResult(prop1) {
return db.task(function (t) {
return t.many("select * from a where prop1=$1", prop1)
.then(function (as) {
var queries = [];
as.forEach(function (a) {
queries.push(t.any("select * from b where b_a=$1", a.id));
});
return t.batch(queries); // could concat queries with as here, but there wouldn't be a reference which b row belongs to which a row
})
.then(function (data) {
// data[n] contains all matching b rows
});
});
}
但是如何将这两者结合起来呢?
【问题讨论】:
-
它们的顺序相同,对吧?所以只需访问
as[n]和data[n]。看看here 如何访问as。 -
感谢您的链接,这可能会有所帮助。但是
a和b之间存在一对多的关系,所以这里的索引没有帮助.. -
batch的返回值是多少?data不是某种二维数组吗? -
刚刚看到它是多维的,在我阅读您的评论之前一秒钟。非常感谢,本来可以早点看到的!
-
where a.a_b is a reference- 表a中没有a_b。
标签: javascript postgresql pg-promise