Anon
Anon

Reputation: 1221

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.

Upvotes: 1

Views: 73

Answers (1)

Mchl
Mchl

Reputation: 62405

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

Upvotes: 3

Related Questions