du0204 2015-06-26 12:11
浏览 61
已采纳

MySQL获取AVR并保存在新字段中

Hello I have this problem and can't find a solution: I have 4 tables with same structure for example as follows:

  1. Table 1: Result
  2. Table 2: Store 1
  3. Table 3: Store 2
  4. Table 4: Store 3

    • Tables fields: ID - Code - Name - Value

I need a query to read the "Value" for each specific record from tables (Store 1 - Store 2 - Store 3) and calculate the average and save it in table (Result)... and go on for the next record until it's done.

Note: I'm using PHP and MySQL...

Thanks in advanced...

SELECT
    result.id,
    result.`code`,
    result.`name`,
    result.value,
    term1.value,
    term2.value,
    term3.value
FROM result
INNER JOIN store1 ON result.`code` = store1.`code`
INNER JOIN store2 ON result.`code` = store2.`code`
INNER JOIN store3 ON result.`code` = store3.`code`
WHERE result.`code` = 123456
ORDER BY result.serial ASC
  • 写回答

2条回答 默认 最新

  • dtntjwkl83750 2015-06-26 12:50
    关注

    The average is just the sum of the values divided by the number of values (3), this is grade school arithmetic.

    UPDATE result AS r
    JOIN store1 AS s1 ON s1.code = r.code
    JOIN store2 AS s2 ON s2.code = r.code
    JOIN store3 AS s3 ON s3.code = r.code
    SET r.value = (s1.value+s2.value+s3.value)/3
    

    To do lots of columns, you can generate the SQL in PHP:

    $cols = array('col1', 'col2', 'col3', ...);
    $sets = implode(', ', array_map(function($col) {
        return "r.$col = (s1.$col + s2.$col + s3.$col)/3";
    }, $cols));
    $sql = "UPDATE result AS r
            JOIN store1 AS s1 ON s1.code = r.code
            JOIN store2 AS s2 ON s2.code = r.code
            JOIN store3 AS s3 ON s3.code = r.code
            SET $sets";
    

    If you're using PHP before 5.3.0, you can define a named function to call it with array_map

    function make_assignment($col) {
        return "r.$col = (s1.$col + s2.$col + s3.$col)/3";
    }
    $sets = implode(', ', array_map('make_assignment', $cols));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?