更新多个字段的最佳方法

时间:2014-02-27 22:30:02

标签: mysql sql

我如何优化这个?     我该如何优化呢?

UPDATE rpt_wrr, ft_2linhas SET rpt_wrr.gchecked = (SELECT SUM(ft_2linhas.checked) FROM ft_2linhas WHERE ft_2linhas.rpt = rpt_wrr.rpt_wrr)

UPDATE rpt_wrr, ft_2linhas SET rpt_wrr.gok = (SELECT SUM(ft_2linhas.ok) FROM ft_2linhas WHERE ft_2linhas.rpt = rpt_wrr.rpt_wrr)

UPDATE rpt_wrr, ft_2linhas SET rpt_wrr.gnok = (SELECT SUM(ft_2linhas.tnok) FROM ft_2linhas WHERE ft_2linhas.rpt = rpt_wrr.rpt_wrr)

UPDATE rpt_wrr, ft_2linhas SET rpt_wrr.grw = (SELECT SUM(ft_2linhas.trw) FROM ft_2linhas WHERE ft_2linhas.rpt = rpt_wrr.rpt_wrr)

UPDATE rpt_wrr SET rpt_wrr.ldchecked = (SELECT SUM(ft_2linhas.Checked) FROM ft_1cab LEFT OUTER JOIN ft_2linhas ON ft_1cab.IDCab = ft_2linhas.IDCab WHERE ft_2linhas.rpt = rpt_wrr.rpt_wrr GROUP BY ft_1cab.Data desc limit 1)

UPDATE rpt_wrr, ft_2linhas SET rpt_wrr.ldok = (SELECT SUM(ft_2linhas.ok) FROM ft_1cab LEFT OUTER JOIN ft_2linhas ON ft_1cab.IDCab = ft_2linhas.IDCab WHERE ft_2linhas.rpt = rpt_wrr.rpt_wrr GROUP BY ft_1cab.Data desc limit 1)

UPDATE rpt_wrr, ft_2linhas SET rpt_wrr.ldnok = (SELECT SUM(ft_2linhas.tnok) FROM ft_1cab LEFT OUTER JOIN ft_2linhas ON ft_1cab.IDCab = ft_2linhas.IDCab WHERE ft_2linhas.rpt = rpt_wrr.rpt_wrr GROUP BY ft_1cab.Data desc limit 1)

UPDATE rpt_wrr, ft_2linhas SET rpt_wrr.ldrw = (SELECT SUM(ft_2linhas.trw) FROM ft_1cab LEFT OUTER JOIN ft_2linhas ON ft_1cab.IDCab = ft_2linhas.IDCab WHERE ft_2linhas.rpt = rpt_wrr.rpt_wrr GROUP BY ft_1cab.Data desc limit 1)

2 个答案:

答案 0 :(得分:1)

您的查询想要像:

UPDATE rpt_wrr r join
       (select ft_2linhas.rpt,
               SUM(ft_2linhas.checked) as checked,
               SUM(ft_2linhas.ok) as ok,
               . . .
        from ft_2linhas
        group by ft_2linhas.rpt
       ) f
       on f.rpt = r.rpt_wrr
     SET r.gchecked = f.checked,
         r.gok = ok;

答案 1 :(得分:0)

我会尝试:

UPDATE
  rpt_wrr INNER JOIN (
    SELECT
      ft_2linhas.rpt,
      SUM(ft_2linhas.checked) As sum_checked,
      SUM(ft_2linhas.ok) As sum_ok,
      SUM(ft_2linhas.tnok) AS sum_tnok,
      SUM(ft_2linhas.trw) AS sum_trw        
    FROM
      ft_2linhas
    GROUP BY
      ft_2linhas.rpt) s
  ON rpt_wrr.rpt_wrr = s.rpt    
SET
  rpt_wrr.gchecked = sum_checked,
  gok = sum_ok,
  gtnok = sum_tnok,
  gtrw = sum_trw

UPDATE
  rpt_wrr INNER JOIN (
    SELECT
      ft_2linhas.rpt,
      SUM(ft_2linhas.checked) As sum_checked,
      SUM(ft_2linhas.ok) As sum_ok,
      SUM(ft_2linhas.tnok) AS sum_tnok,
      SUM(ft_2linhas.trw) AS sum_trw        
    FROM
      ft_1cab INNER JOIN ft_2linhas ON ft_1cab.IDCab = ft_2linhas.IDCab
    GROUP BY
      ft_2linhas.rpt) s
  ON rpt_wrr.rpt_wrr = s.rpt
SET
  rpt_wrr.ldchecked = sum_checked,
  ldok = sum_ok,
  ldtnok = sum_tnok,
  ldtrw = sum_trw

(但由于我不知道你的数据库是如何构建的,我不知道ft_1cab INNER JOIN ft_2linhas在这里是否有意义