简体   繁体   中英

Can't use a sub-query inside an UPDATE query?

When I use this query, MySQL display me the "HY000" error : "You can't specify target table 'msg_pv' for update in FROM clause".

The problem seems to be that the query and sub-query aim the same table... but this is what I need to do !

 <?php  $requete = $pdo->prepare('UPDATE msg_pv SET 
        lu=:lu
        WHERE id_ref_msg = :id_ref_msg AND date_message > ( SELECT MIN(date_message) FROM msg_pv WHERE id_ref_msg = :id_ref_msg AND lu="0" )');

NOTE: I've read some solutions into other posts with INNER JOIN but it was for different tables.

Try like this

UPDATE
  msg_pv AS t1
CROSS JOIN (
  SELECT MIN(date_message) AS date_message FROM msg_pv
  WHERE id_ref_msg = :id_ref_msg AND lu="0"
) AS t2
SET
  t1.lu = :lu
WHERE
  t1.date_message > t2.date_message

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM