Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner join on delete query, Node JS, Knex JS

This query works:

  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() gives:

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'

This query does not work:

  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() gives:

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

Not possible to use join on delete queries? Do you I have to make a separate query to join them?

like image 465
Joe Avatar asked Jul 03 '14 08:07

Joe


1 Answers

Seems a delete join isn't working correctly (possibly due to very different delete join syntax for various databases), but you should be able to rewrite the query as a simple IN query;

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

...which should be generated by (the untested);

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()

...and always remember to back up your data before running potentially destructive SQL from random people on the Internet on your database ;-)

like image 142
Joachim Isaksson Avatar answered Sep 23 '22 08:09

Joachim Isaksson