如何修复选择并更新到同一个表

时间:2013-07-25 08:25:17

标签: mysql select

update moodlesocialuser 
set moodlesocialuser.deleted=deleted+1 
where id IN (
  select m1.id 
  from moodlesocialuser m1 
  join moodlesocialpost m2 on m1.id=m2.userid 
  where m2.module='blog' 
  and m1.deleted='0' 
  and url like 'http%' 
  and m1.id NOT IN (
    select id from moodlesocialcourse_display
  ) 
);

我无法进行更新并从同一张表中选择。

  

错误1093(HY000):您无法在FROM子句中指定目标表'moodlesocialuser'以进行更新。

我该怎么做?

4 个答案:

答案 0 :(得分:0)

如果此查询中没有聚合函数,为什么使用group by子句? 注释掉group by子句和脚本将运行没有任何错误。

答案 1 :(得分:0)

看起来您在该UPDATE语句中复制粘贴现有查询。您可以在第一个子查询中删除m1别名,如下所示:

update moodlesocialuser 
set moodlesocialuser.deleted=deleted+1 
where id IN (
  select m2.userid
  where m2.module='blog' 
  and url like 'http%'
)
and moodlesocialuser.deleted='0' 
and id NOT IN (
    select id from moodlesocialcourse_display
)

答案 2 :(得分:0)

错误消息显示,您正在尝试更新您正在阅读的表格。

使用临时表:

create temporary table foo (id int);

insert into foo 
  select m1.id 
  from moodlesocialuser m1 
  join moodlesocialpost m2 on m1.id=m2.userid 
  where m2.module='blog' 
  and m1.deleted='0' 
  and url like 'http%' 
  and m1.id NOT IN (
    select id from moodlesocialcourse_display
  ) 
;

update moodlesocialuser m
inner join foo on m.id = foo.id
set m.deleted=deleted+1 
;

drop table foo;

答案 3 :(得分:0)

您无法修改从(read more here)中选择的表格;另一方面,我认为你可以摆脱那个子查询,就像这样(我不认为下面的查询会真正起作用,你最好在非有价值的数据上测试它;我想说的是 - 你是也可以加入更新):

UPDATE moodlesocialuser mu, moodlesocialcourse_display md, moodlesocialpost mp
SET mu.deleted=mu.deleted + 1 
WHERE
md.id != mu.id AND
mu.deleted = 0 AND
mp.userid = mu.id AND
mp.module = 'blog' AND
mp.url LIKE 'http%'