[英]In sequelize, how do I select records that match different values of multiple rows?
As an example, I have the following table: 例如,我有下表:
A | B
------
1 | 2
1 | 3
1 | 4
2 | 3
2 | 4
3 | 3
I want to select all values in B that have the value 1 AND 2 in the A Column. 我想选择B列中A列中值为1 AND 2的所有值。 So in the above example I should get as a result (3,4) because only 3 and 4 have for column A the values 1 and 2.
因此,在上面的示例中,我应该得到结果(3,4),因为对于列A,只有3和4的值分别为1和2。
How would I do this in sequelize? 我该如何续作呢?
This is what I tried: 这是我尝试的:
db.myModel.findAll({
where: {
A: whatImSearching
},
attributes: ['A', 'B']
})
with whatImSearching = [1,2]
与
whatImSearching = [1,2]
But that solution returns results where only one of the values match, ie I would get as a result (2,3,4). 但是该解决方案返回的结果中只有一个值匹配,即我将得到结果(2,3,4)。 But I should only get (3,4).
但是我只能得到(3,4)。
Note: This is how it can be done in SQL, like @daf mentioned in comments, something on similar lines can be implemented in Sequelize. 注意:这是可以在SQL中完成的方式,就像注释中提到的@daf一样,可以在Sequelize中实现类似内容。 I've kept this around as a reference
我一直将此作为参考
You can use group by with conditional having like this 您可以像这样有条件地使用分组方式
SELECT B
FROM Table1 GROUP BY B
HAVING SUM(CASE WHEN A IN(1,2) THEN 1 ELSE 0 END) = 2
EDIT 编辑
Assuming your have duplicate values. 假设您有重复的值。 this should be better
这应该更好
SELECT B
FROM Table1 GROUP BY B
HAVING SUM(CASE WHEN A = 1 THEN 1 ELSE 0 END) = 1
AND SUM(CASE WHEN A = 2 THEN 1 ELSE 0 END) = 1
Edit: I'm not immediately seeing a pure Sequelize way to do this, however the below should get where you want with the small hit of bringing back some extra rows from the database. 编辑:我不会立即看到一种纯粹的Sequelize方法来执行此操作,但是下面的代码应该可以从数据库中带回一些额外的行,从而达到您想要的位置。
Assuming that you're doing the query using a model like: 假设您使用以下模型进行查询:
var model = sequelize.define('model', {
A: { type: Sequelize.TEXT },
B: { type: Sequelize.TEXT }
}, {
tableName: 'SomeTable',
timestamps: false
})
you can do: 你可以做:
var search = [1,2];
model.findAll({
where: { A: { '$in': search } },
attributes: ['A', 'B']
}).then(function(instances) {
var unwrapped = instances.map(function(i) {
return i.get();
});
var withCounts = unwrapped.reduce(function(acc, cur) {
var thisB = cur.B;
var accItem = acc.filter(function(i) {
return i.B === thisB;
})[0];
if (!accItem) {
accItem = { B: thisB, count: 0 };
acc.push(accItem);
}
accItem.count++;
}, [])
var hasAll = withCounts.filter(function(i) {
return i.count === search.length;
}).map(function(i) {
return i.B;
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.