1

我有这样的查询

UPDATE `user_plan_details` 
SET    `plan_expiry_date` = Date_add((SELECT plan_expiry_date 
                                      FROM   `user_plan_details` 
                                      WHERE  user_id = 56 
                                             AND 
                                     user_plan_details.is_current_plan = 1) 
                                   , INTERVAL 30 day) 
WHERE  `user_id` = '56' 
       AND user_plan_details.is_current_plan = 1 

执行此查询时收到这样的错误消息

MySQL 数据库错误:您无法在 FROM 子句中指定目标表 'user_plan_details' 进行更新

子查询

SELECT DATE_ADD((SELECT plan_expiry_date FROM `user_plan_details` WHERE user_id = 56 AND user_plan_details.is_current_plan = 1 ), INTERVAL 30 DAY)

给出结果

1/11/2013 12:00:00 AM

我的查询有什么问题?请帮我。

4

3 回答 3

1

请参阅子查询错误“子查询中不正确使用的表”中的最后一项。

它说您可以在更新语句中使用子查询,但不能在更新和子选择中使用同一个表。

但是你可以试试这个

UPDATE `user_plan_details` 
SET    `plan_expiry_date` = Date_add(plan_expiry_date, INTERVAL 30 day) 
WHERE  `user_id` = '56' 
       AND user_plan_details.is_current_plan = 1 

用于测试的SQL Fiddle 。

于 2012-12-04T06:45:57.650 回答
1

原因是您正在更新一个表,您从该表的子查询中获取其记录。MYSQL 不允许这样做,您需要通过动态创建临时表来欺骗数据库

你可以简单::

UPDATE `user_plan_details` 
SET    `plan_expiry_date` = Date_add(plan_expiry_date, INTERVAL 30 day) 
WHERE  `user_id` = '56' 
       AND user_plan_details.is_current_plan = 1

或者如果你想以你的风格::作为::

UPDATE `user_plan_details` 
SET    `plan_expiry_date` = Date_add(
Select temp_itself.plan_expiry_date from 
(SELECT plan_expiry_date 
                                      FROM   `user_plan_details` 
                                      WHERE  user_id = 56 
                                             AND 
                                     user_plan_details.is_current_plan = 1) 
                                   , INTERVAL 30 day) temp_itself
WHERE  `user_id` = '56' 
       AND user_plan_details.is_current_plan = 1 
于 2012-12-04T06:49:42.237 回答
0

你可以这样做:

update user_plan_details as t1, (select DATE_ADD((SELECT plan_expiry_date FROM 
   `user_plan_details` WHERE  user_id = 56 AND user_plan_details.is_current_plan = 1 ),
    INTERVAL 30 DAY) as t2 ) as t3  set t1.plan_expiry_date=t3.t2 where t1.`user_id` = 
    '56' AND t1.is_current_plan = 1 ;
于 2012-12-04T07:03:27.860 回答