ERROR 1241(21000)和ERROR 1093(HY000)阻止执行MYSQL子查询

时间:2014-07-04 11:52:25

标签: mysql sql database subquery

我在这里提供mysql查询: -

mysql> UPDATE tbl_driver SET active_flag=NULL WHERE Pk_driver_id = (SELECT Pk_driver_id FROM tbl_driver JOIN tbl_location ON tbl_driver.pk_driver_id = tbl_location.fk_driver_id WHERE updated_at <= NOW() - INTERVAL 3 MINUTE AND active_flag=1);



ERROR 1093 (HY000): You can't specify target table 'tbl_driver' for update in FROM clause

所以我改变了我的子查询以选择*:

mysql> UPDATE tbl_driver SET active_flag=NULL WHERE Pk_driver_id = (SELECT * FROM tbl_driver JOIN tbl_location ON tbl_driver.pk_driver_id = tbl_location.fk_driver_id WHERE updated_at <= NOW() - INTERVAL 3 MINUTE AND active_flag=1);



ERROR 1241 (21000): Operand should contain 1 column(s).

请帮我解决这个问题,提前致谢。

2 个答案:

答案 0 :(得分:0)

您正在尝试将set与单行值匹配,您希望将其与subselect中出现的所有值进行匹配,即使它始终是单值。 IN是允许您匹配集合中的值的关键字。

UPDATE tbl_driver SET active_flag=NULL
WHERE Pk_driver_id IN (
    SELECT Pk_driver_id FROM tbl_driver
    JOIN tbl_location ON tbl_driver.pk_driver_id = tbl_location.fk_driver_id
    WHERE updated_at <= NOW() - INTERVAL 3 MINUTE AND active_flag=1);

答案 1 :(得分:0)

使用INNER JOIN代替子选择应该使您的更新有效:

UPDATE 
    tbl_driver 
INNER JOIN 
    tbl_location 
ON 
    tbl_driver.pk_driver_id = tbl_location.fk_driver_id
SET tbl_driver.active_flag = NULL
WHERE
    updated_at <= NOW() - INTERVAL 3 MINUTE 
AND 
    tbl_driver.active_flag = 1;

MySQL目前(版本5.6)对use of subqueries in UPDATE statements

的限制
  

目前,您无法更新表并从子查询中的同一表中进行选择。