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!
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With