我正在尝试从具有最高
WPM
和accuracy
的用户那里检索测试,时间为60 seconds
。我设法以最高的 WPM 和准确性获得了测试。如果有两个具有相同 wpm 和准确度的测试,则使用 createdAt
日期来选择一个测试,因此选择具有较早 createdAt 日期的测试。问题是,如果有两个测试具有相同的 WPM 和准确性,并且有第三个测试具有更高的 WPM,则查询无法返回任何测试。
这是查询生成器:
const qb = ctx.em
.createQueryBuilder(Test, 'test')
.innerJoin(
(subQuery) =>
subQuery
.select('MAX(t.wpm)', 'max_wpm')
.addSelect('t.creatorId', 'creatorId')
.addSelect('MAX(t.accuracy)', 'max_accuracy')
.from(Test, 't')
.where('t.time = :time', { time: '60' })
.groupBy('t.creatorId'),
'max_tests',
'max_tests.max_wpm = test.wpm AND max_tests."creatorId" = test."creatorId" AND max_tests.max_accuracy = test.accuracy'
)
.leftJoinAndSelect('test.creator', 'creator')
.where('test.time = :time', { time: '60' })
.andWhere((qb) => {
const subQuery = qb
.subQuery()
.select('MIN(t2.createdAt)')
.from(Test, 't2')
.where('t2.creatorId = test.creatorId')
.andWhere('t2.wpm = test.wpm')
.andWhere('t2.accuracy = test.accuracy')
.getQuery();
return `test."createdAt" = (${subQuery})`;
})
.orderBy('test.wpm', 'DESC')
.addOrderBy('test.accuracy', 'DESC')
这里是三个示例测试:
[
{
"id": 1,
"wpm": 96,
"accuracy": 96.7,
"time": "60",
"createdAt": "2023-05-09T11:26:42.003917Z",
"creatorId": 1
},
{
"id": 2,
"wpm": 96,
"accuracy": 96.7,
"time": "60",
"createdAt": "2023-05-09T12:58:48.956275Z",
"creatorId": 1
},
{
"id": 3,
"wpm": 97,
"accuracy": 97,
"time": "60",
"createdAt": "2023-05-09T13:18:21.991219Z",
"creatorId": 1
}
]
预期的结果是获得测试 #3,但我当前的代码无法返回任何内容。
如何修改我的查询?
数据库:postgreSQL orm:typeorm