Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to specify other tables in an update statement #60

Closed
cmoad opened this issue Apr 12, 2018 · 2 comments
Closed

How to specify other tables in an update statement #60

cmoad opened this issue Apr 12, 2018 · 2 comments

Comments

@cmoad
Copy link
Contributor

cmoad commented Apr 12, 2018

From the postgres spec:

[ WITH [ RECURSIVE ] with_query [, ...] ]
UPDATE [ ONLY ] table_name [ * ] [ [ AS ] alias ]
    SET { column_name = { expression | DEFAULT } |
          ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
          ( column_name [, ...] ) = ( sub-SELECT )
        } [, ...]
    [ FROM from_list ]
    [ WHERE condition | WHERE CURRENT OF cursor_name ]
    [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]

I'm unable to figure out how to add [ FROM from_list ] items. I'm attempting to do a simple join on the update. Attempting to build something like this:

update user_groups set role = ? from groups where user_groups.group_id = groups.id and groups.account_id = ? and user_groups.id = ?

Please don't look too much into this example. There are lots of uses for joins during update.

@doug-martin
Copy link
Owner

With v8 #110 this will be easier to accomplish, Ill look into adding this next.

doug-martin added a commit that referenced this issue Jul 25, 2019
* [ADDED] Multi table update support for `mysql` and `postgres` #60
@doug-martin doug-martin mentioned this issue Jul 25, 2019
@doug-martin
Copy link
Owner

This will be in the next release v8.0.1. I added support for both postgres and mysql.

Examples:

Postgres

dialect := goqu.Dialect("postgres")

ds := dialect.Update("table_one").
    Set(goqu.Record{"foo": goqu.I("table_two.bar")}).
    From("table_two").
    Where(goqu.Ex{"table_one.id": goqu.I("table_two.id")})

sql, _, _ := ds.ToSQL()
fmt.Println(sql)

Output:

UPDATE "table_one" SET "foo"="table_two"."bar" FROM "table_two" WHERE ("table_one"."id" = "table_two"."id")

MySQL

dialect := goqu.Dialect("mysql")

ds := dialect.Update("table_one").
    Set(goqu.Record{"foo": goqu.I("table_two.bar")}).
    From("table_two").
    Where(goqu.Ex{"table_one.id": goqu.I("table_two.id")})

sql, _, _ := ds.ToSQL()
fmt.Println(sql)

Output:

UPDATE `table_one`,`table_two` SET `foo`=`table_two`.`bar` WHERE (`table_one`.`id` = `table_two`.`id`)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants