编程语言
首页 > 编程语言> > javascript – 使用Knex.js的select语句的子查询

javascript – 使用Knex.js的select语句的子查询

作者:互联网

我正在尝试使用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”列但总是为零,可能是因为它没有识别子查询中的’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.ID字符串作为值传递.为了能够做.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);

标签:javascript,mysql,node-js,sql-server,knex-js
来源: https://codeday.me/bug/20190519/1133730.html