gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:08:39 25 4
gpt4 key购买 nike

您好,我遇到这个问题,找不到解决方案:我有 4 个具有相同结构的表,例如如下:

  1. 表 1:结果
  2. 表 2:商店 1
  3. 表 3:商店 2
  4. 表 4:商店 3

    • 表字段:ID - 代码 - 名称 - 值

我需要一个查询来读取表中每个特定记录的“值”(存储 1 - 存储 2 - 存储 3)并计算平均值并将其保存在表中(结果)...并继续下一条记录,直至完成。

注意:我正在使用 PHP 和 MySQL...

提前致谢...

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

最佳答案

平均值只是值的总和除以值的数量 (3),这是小学算术。

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

要处理大量列,您可以在 PHP 中生成 SQL:

$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";

如果您使用 5.3.0 之前的 PHP,您可以定义一个命名函数来使用 array_map 调用它

function make_assignment($col) {
return "r.$col = (s1.$col + s2.$col + s3.$col)/3";
}
$sets = implode(', ', array_map('make_assignment', $cols));

关于php - MySQL 获取 AVR 并保存在新字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31072884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com