mysql子查询在更新查询

时间:2017-08-31 12:31:41

标签: mysql

我运行了以下查询并收到错误您无法在FROM子句

中指定更新目标表
update xyz x 
set x.PID = (select c.PPID 
            from 
            table1 c where c.FFID 
            in (select b.FID 
                from table1 a 
                join xyz b on a.FFID = b.fID 
                and a.FFIRD=b.PID and b.flag='4' 
                group by b.FID 
                having count(1) =1)
               ),flag='N' 
where x.FID = (select b.FID 
               from table1 a join xyz b on
               a.FFID = b.FID and 
               a.FFIRD=b.PID and b.flag='4' 
               group by b.FID 
               having count(1) =1
              )

我引用了stackoverflow并改变了我的代码,如下所示。但现在我得到Subquery返回超过1行。请帮忙

update xyz x 
set x.PID = (select abc.PPID 
            from (select c.PPID 
                  from 
                  table1 c 
                  where c.FFID 
                  in (select b.FID 
                      from 
                      table1 a join xyz b on a.FFID = b.fID 
                      and a.FFIRD=b.PID and b.flag='4' 
                      group by b.FID 
                      having count(1) =1
                      ) as abc
                      ),flag='N' 
where x.FID = (select xyz.FID 
               from (select b.FID 
                     from table1 a join xyz b on
                     a.FFID = b.FID and 
                     a.FFIRD=b.PID and b.flag='4' 
                     group by b.FID 
                     having count(1) =1)as xyz
               )

1 个答案:

答案 0 :(得分:0)

根据您的工作脚本,您可以创建一个CTE并将数据转换为该数据,然后根据这些或那些变化进行更新:

 WITH YourCTE (PPID)
 AS
 (select c.PPID 
        from 
        table1 c where c.FFID 
        in (select b.FID 
            from table1 a 
            join xyz b on a.FFID = b.fID 
            and a.FFIRD=b.PID and b.flag='4' 
            group by b.FID 
            having count(1) =1)
           ),flag='N' 
 where x.FID = (select b.FID 
           from table1 a join xyz b on
           a.FFID = b.FID and 
           a.FFIRD=b.PID and b.flag='4' 
           group by b.FID 
           having count(1) =1
          )
 )
UPDATE xyz x 
SET x.PID = (SELECT PPID FROM YourCTE)