不能在UPDATE查询中使用子查询?

时间:2022-09-23 12:33:04

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

当我使用此查询时,MySQL显示“HY000”错误:“您无法在FROM子句中为更新指定目标表'msg_pv'”。

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.

注意:我已经通过INNER JOIN阅读了其他帖子的一些解决方案,但它适用于不同的表格。

1 个解决方案

#1


3  

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

#1


3  

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