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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效