1

In SQL server we can update set join like this,

Update table1 set column = n.newvalue from table1 join (values('value1', 'value2')) N (oldvalue, newvalue) on table1.column = oldvalue

I try to write something like this is mySQL, different from SQL server mySQL use something like this

update table join table2 on table1.column = table2.column set table1.column = table2.column

So I tried to write it like this

update table1 join (values('value1','value2')) N (oldvalue, newvalue) on table.column = n.oldvalue
set table.column = n.newcolumn

but I always get the error check the manual that corresponds to your MySQL server version for the right syntax to use near 'VALUES, so is there something I can use other than values, or is there another method of writing this query

jww
  • 97,681
  • 90
  • 411
  • 885
  • 2
    You will need a subquery with its own `SELECT` as shown in https://stackoverflow.com/a/985299/2055998 – PM 77-1 Dec 27 '19 at 02:27

2 Answers2

1

MySQL does not support the table value constructor which is available in SQL Server. The closest alternative, assuming you are using MySQL 8+, might be to use a CTE:

WITH N (oldvalue, newvalue) AS (
    SELECT 'value1', 'value2'
)

UPDATE table1 t1
INNER JOIN N n
    ON t1.column = n.oldvalue
SET
    t1.column = n.newcolumn;

This approach still requires an explicit reference to SELECT (table value constructor does not), but it at least lets you keep the literal value in a logically separate segment of code.

On earlier versions of MySQL, you would have to inline the above CTE as subquery, giving you:

UPDATE table1 t1
INNER JOIN
(
    SELECT 'value1' AS oldvalue, 'value2' AS newvalue
) n
    ON t1.column = n.oldvalue
SET
    t1.column = n.newcolumn;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

I'm wondering why you don't just write the query like this:

Update table1
    set column = 'value2'
    where column = 'value1';

This will work in any database.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786