Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Sequel, can I create UPDATE statements with a FROM clause

Tags:

sql

ruby

sequel

Using Sequel I'd like to create an UPDATE statement like the following (from Postgres docs)

UPDATE employees SET sales_count = sales_count + 1 FROM accounts
  WHERE accounts.name = 'Acme Corporation'
  AND employees.id = accounts.sales_person;

However, looking at the Sequel documentation it's not clear where there's any way to create the FROM clause.

Is there a way to do this?

Thanks!

like image 425
brahn Avatar asked Feb 02 '13 01:02

brahn


2 Answers

OK, Ben Lee's answer got me going in the right direction. Solution:

DB[:employees].from(:employees, :accounts).
  where(:accounts__name => 'Acme Corporation').
  update_sql(:employees__sales_count => "employees.sales_count + 1".lit)

I'm a bit uncertain about the use of .lit here, but it does seem to do the trick. (Also, I'm using update_sql rather than update to produce the SQL output rather than running the command.)

Result, as desired:

UPDATE "employees" 
   SET "employees"."sales_count" = employees.sales_count + 1 
  FROM "accounts"
 WHERE ("accounts"."name" = 'Acme Corporation')
like image 179
brahn Avatar answered Oct 03 '22 08:10

brahn


Everybody else's answers have one tiny superfluous clause.

DB.from(:employees, :accounts).
  where(:accounts__name => 'Acme Corporation').
  update_sql(:employees__sales_count => "employees.sales_count + 1".lit)

If you're doing a from() with two tables, then the one inside the DB[...] is ignored.

like image 35
ColinK Avatar answered Oct 03 '22 06:10

ColinK