使用另一个表中另一个字段的值更新表中的字段

时间:2018-09-23 15:37:46

标签: mysql sql sql-update subquery

我需要用relevo表的最后110个值更新descricao_geral表的最后110个值

我正在这样做:

UPDATE descricao_geral
SET id_relevo_fk = (SELECT id_relevo FROM relevo ORDER BY id_relevo DESC LIMIT 110) 
ORDER BY id_descricao DESC
LIMIT 110

我收到的错误:

  

子查询返回1行以上

1 个答案:

答案 0 :(得分:1)

这真的很棘手。您需要将表连接在一起,但是没有适当的键。

您可以使用变量分配顺序值,然后将其用于join

update descricao_geral g join
       (select (@rng := @rng + 1) as rn, g2.id_descricao
        from (select g2.* from descricao_geral g2 order by g2.id_descricao desc) g2 cross join
             (select @rng := 0) params
        limit 110
       ) g2
       on g.id_descricao = g2.id_descricao join
       (select (@rnr := @rnr + 1) as rn, r.id_relevo
        from (select r.* from relevo r order by r.id_relevo desc) r cross join
             (select @rnr := 0) params
       ) r
       on g2.rn = r.rn
   set g.id_relevo_fk = r.id_relevo;