Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPDATE with INNER JOIN fails but related SELECT statement works

Is there a reason why the following UPDATE statement produces an error

UPDATE `t1`
INNER JOIN `t2` ON `t2`.`id`=`t1`.`t2_id`
INNER JOIN `t3` ON `t2`.`t3_id` = `t3`.`id` AND `t3`.`a_id` = '123'
WHERE `t2`.`date` > '2012-08-14'
    AND `t2`.`status` = 'pending'
SET `t1`.`active` = '0';

The error I get is:

#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 'WHERE `t2`.`date` > '2012-08-14' AND `t2`.`statu' at line 4

The following (related) SELECT statement works okay

SELECT `t1`.*
FROM `t1`
INNER JOIN `t2` ON `t2`.`id`=`t1`.`t2_id`
INNER JOIN `carer` ON `t2`.`t3_id` = `t3`.`id` AND `t3`.`a_id` = '123'
WHERE `t2`.`date` > '2012-08-14'
    AND `t2`.`status` = 'pending'
like image 904
xylar Avatar asked Sep 05 '25 03:09

xylar


1 Answers

The MySQL UPDATE syntax is:

UPDATE [LOW_PRIORITY] [IGNORE] table_references  
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...  
    [WHERE where_condition]  

Use this:

UPDATE `t1`
INNER JOIN `t2` ON `t2`.`id`=`t1`.`t2_id`
INNER JOIN `t3` ON `t2`.`t3_id` = `t3`.`id` AND `t3`.`a_id` = '123'

SET `t1`.`active` = '0'

WHERE `t2`.`date` > '2012-08-14'
    AND `t2`.`status` = 'pending' ;
like image 50
ypercubeᵀᴹ Avatar answered Sep 07 '25 16:09

ypercubeᵀᴹ