select语句的子查询与Knex.js

我正在尝试使用Knex创build子查询的以下查询:

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_users,team_access)的UserCount和AppCount的计数聚合的团队表,

 id | Name | OwnerUserID | UserCount | AppCount ----------------------------------------------------- 134| Team A | 1538 | 7 | 6 135| Team B | 1538 | 4 | 2 136| Team C | 1538 | 12 | 1 

我认为是一个等同的实施是:

 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”列,但总是为零,可能是因为它没有标识子查询中的“teams.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); 

但我很好奇,知道如何实现与子查询对象。

您正尝试将teams.IDstring作为值传递。 为了能够执行.where('columnName', 'otherColumnName') ,必须使用knex.raw来传递otherColumnName作为标识符。

 var teamsIdColumnIdentifier = knex.raw('??', ['teams.ID']); 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);