Question

I have the following SQL code:

SELECT
    `table1`.`field1`
    , `view1`.`newfield1`
FROM
    `table1`
INNER JOIN `GCOTDA2`.`view1` 
        ON (`table1`.`id1` = `view1`.`id1`) AND (`table1`.`id2` = `view1`.`id2`);

The query works fine but now I want to copy the view1.newfield1 to table1.field1. Thus, I wrote the following statement:

UPDATE `table1`
SET
    `table1`.`field1` = `view1`.`newfield1`
FROM
    `table1`
INNER JOIN `view1` 
        ON (`table1`.`id1` = `view1`.`id1`) AND (`table1`.`id2` = `view1`.`id2`);

However, the update does not work and I got this error message:

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM
    `table1`
    INNER JOIN `view1` 
 ' at line 4

I checked on google and other questions in this site such as: How do I UPDATE from a SELECT in SQL Server? and Error Code: 1064 in mysql with no luck. (MySQL Server 5.5.27) I need someone to illuminate me, thanks!

Was it helpful?

Solution

Try this on for size:

UPDATE 'table1` t JOIN `view1` v 
ON      t.id1 = v.id1 AND t.id2 = v.id2
SET     t.field1 = v.newfield1

OTHER TIPS

You can do this with a subquery:

update 
    table1
set
    table1.field1 = (select view1.newfield1 from view1 where view1.id1 = table1.id1 and view1.id2 = table1.id2)
where
    exists (select null from view1 where view1.id1 = table1.id1 and view1.id2 = table1.id2)

http://sqlfiddle.com/#!2/64774/1/0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top