Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a table joining another table

Tags:

mysql

Update a table joining 1 more table.

UPDATE t1 SET  t1.col1 =1 FROM table1 t1 JOIN  table2 t2 
ON t1.ID=t2.ID
WHERE t1.Name='Test' AND t2.Age=25;

i get this error,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 t1 JOIN table2 t2 ...

Any thoughts?

Thanks.

like image 243
Sharpeye500 Avatar asked Sep 23 '10 23:09

Sharpeye500


1 Answers

There shouldn't be a FROM clause in the UPDATE statement, and the SET clause should follow the full set of table references:

UPDATE  table1 t1 
JOIN    table2 t2 ON t1.ID = t2.ID
SET     t1.col1 = 1
WHERE   t1.Name = 'Test' AND t2.Age = 25;

Test case:

CREATE TABLE table1 (id int, col1 int, name varchar(20));
CREATE TABLE table2 (id int, age int);

INSERT INTO table1 VALUES (1, 0, 'Test');
INSERT INTO table1 VALUES (2, 0, 'Test');
INSERT INTO table1 VALUES (3, 0, 'No Test');

INSERT INTO table2 VALUES (1, 20);
INSERT INTO table2 VALUES (2, 25);
INSERT INTO table2 VALUES (3, 25);

Result:

SELECT * FROM table1;
+------+------+---------+
| id   | col1 | name    |
+------+------+---------+
|    1 |    0 | Test    |
|    2 |    1 | Test    |
|    3 |    0 | No Test |
+------+------+---------+
3 rows in set (0.00 sec)
like image 96
Daniel Vassallo Avatar answered Oct 11 '22 18:10

Daniel Vassallo