内部连接删除查询,Node JS,Knex JS

时间:2014-07-03 08:49:49

标签: node.js postgresql knex.js

此查询有效:

  var query = knex('project_member')
    .join('project', 'project_member.pm_project', '=', 'project.prj_id')
    .join('users', 'project_member.pm_user', '=', 'users.us_id')
    .where({
      prj_number: inputs.params.prj_number
    })
    .select('pm_project', 'us_name', 'us_alias');

query.toString()给出:

select "pm_project", "us_name", "us_alias" from "project_member" inner join "project" on "project_member"."pm_project" = "project"."prj_id" inner join "users" on "project_member"."pm_user" = "users"."us_id" where "prj_number" = '4026305'

此查询不起作用:

  var query = knex('project_member')
    .join('project', 'project_member.pm_project', '=', 'project.prj_id')
    .where({
      prj_number: inputs.params.prj_number,
      pm_user: inputs.params.pm_user
    })
    .del();

query.toString()给出:

delete from "project_member" where "prj_number" = '4026305' and "pm_user" = '1'

无法在删除查询中使用联接?您是否必须单独进行查询以加入它们?

1 个答案:

答案 0 :(得分:1)

似乎删除连接无法正常工作(可能是由于各种数据库的删除连接语法非常不同),但您应该能够将查询重写为简单的IN查询;

DELETE FROM project_member
WHERE pm_user = <pm user>
AND pm_project IN (
  SELECT prj_id FROM project WHERE prj_number = <prj_number>
)

...应该由(未经测试的)生成;

knex('project_member')
  .where('pm_user', inputs.params.pm_user)
  .whereIn('pm_project', function() {
    this.select('prj_id')
        .from('project')
        .where('prj_number', inputs.params.prj_number);
  })
  .del()

...并且始终记得在数据库上从Internet上的随机用户运行可能具有破坏性的SQL之前备份数据; - )