【问题标题】:Knex to join tables from two databasesKnex 连接来自两个数据库的表
【发布时间】:2017-06-29 09:15:25
【问题描述】:

我是 Node.js 的新手。我正在使用 Knex 进行查询。我需要连接来自两个不同数据库的两个表。谁能告诉我这是怎么可能的?

knex.select('id', 'full_name','email', 'mobile_country_code', 'mobile', knex.raw('1 as active_status')).from('users').where(whereData).union(function() {
        this.select('id','full_name', 'email', 'mobile_country_code', 'mobile', knex.raw('0 as active_status')).from('users_temp').where(whereData);
    }).then(function(data) {
        next(null, data);
    }).catch(function(err) {
        next(err.toString());
    });

【问题讨论】:

  • 您能否添加您尝试创建的普通 SQL 查询的简单案例?
  • ( SELECT u1.id, u1.full_name, u1.email, u1.mobile_country_code, u1.mobile, 1 AS active_status, u2.user_timeline_pic FROM db1.users AS u1 JOIN db2.users AS u2 ON u1.id = u2.id) UNION (SELECT id, full_name, email, mobile_country_code, mobile, 0 AS active_status, 'default/user_profile_pic.png' AS user_timeline_pic FROM db1.users)
  • 我需要的已经在上面了。感谢您的回复@Mikael Lepistö

标签: mysql node.js knex.js


【解决方案1】:
knex
  .select(
    'users.id','users.full_name', 'users.email',
    'users.mobile_country_code', 'users.mobile',
    'loc.user_profile_pic', 'loc.user_timeline_pic'
  )
  .from('users')
  .leftJoin(config.project_db + '.users as loc', 'loc.id', '=', 'users.id')
  .where(whereData).union(function() {
    this.select(
      'id','full_name', 
      knex.raw('\''+constants.images.default_user_profile_pic+'\' as user_profile_pic, \''+constants.images.default_user_timleline_pic+'\' as user_timeline_pic'),
      'email', 'mobile_country_code', 'mobile'
    )
    .from('users_temp').where(whereData);
  });

【讨论】:

  • 这个“config.project_db”是从哪里来的?如果我在那里简单地使用我的 knex 参考,它就不起作用
猜你喜欢
  • 2014-10-05
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-27
  • 2018-03-22
相关资源
最近更新 更多