我正在尝试使用Knex使用子查询创建以下查询:
SELECT
t.*,
(SELECT COUNT(*) FROM team_users tu WHERE TeamID = t.ID) AS UserCount,
(SELECT COUNT(*) FROM team_access ta WHERE TeamID = t.ID) AS AppCount
FROM teams t WHERE OwnerUserID = _UserID;
结果应该是team表,其中包含来自不同表的UserCount和AppCount的计数聚合(team_users,team_access)
id | Name | OwnerUserID | UserCount | AppCount
-----------------------------------------------------
134| Team A | 1538 | 7 | 6
135| Team B | 1538 | 4 | 2
136| Team C | 1538 | 12 | 1
我认为是一个等效的knex实现是:
var subquery1 = Knex.knex('team_users').count('*').where('TeamID', 'teams.ID').as('UserCount');
var subquery2 = Knex.knex('team_access').count('*').where('TeamID', 'teams.ID').as('AppCount');
Knex.knex.select('*', subquery1, subquery2).from('teams').where("OwnerUserID", ownerId).asCallback(dataSetCallback);
运行它,我确实得到了" UserCount"和" AppCount"返回对象中的列但始终为零,这可能是因为它没有识别出&team; ID。在子查询中。
我设法使用Knex.raw函数解决了它:
Knex.knex('teams')
.select('*', Knex.knex.raw('(SELECT COUNT(*) FROM team_users WHERE TeamID = teams.ID) AS UserCount'), Knex.knex.raw('(SELECT COUNT(*) FROM team_access WHERE TeamID = teams.ID) AS AppCount'))
.where("OwnerUserID", ownerId)
.asCallback(dataSetCallback);
但我很想知道如何使用子查询对象来实现这一点。
答案 0 :(得分:7)
您正在尝试将teams.ID
字符串作为值传递。为了能够.where('columnName', 'otherColumnName')
,必须使用knex.ref
来传递otherColumnName
作为标识符。
var teamsIdColumnIdentifier = knex.ref('teams.ID'); // <-- [1]
var subquery1 = Knex.knex('team_users').count('*')
.where('TeamID', teamsIdColumnIdentifier).as('UserCount');
var subquery2 = Knex.knex('team_access').count('*')
.where('TeamID', teamsIdColumnIdentifier).as('AppCount');
Knex.knex.select('*', subquery1, subquery2).from('teams')
.where("OwnerUserID", ownerId).asCallback(dataSetCallback);
[1]在May 2018中将knex.ref
添加到Knex之前,您必须使用knex.raw
,就像这样;
var teamsIdColumnIdentifier = knex.raw('??', ['teams.ID']);