您好我遇到此问题但无法找到解决方案: 我有4个具有相同结构的表,例如如下:
表4:存储3
我需要一个查询来阅读" Value"对于表格中的每个特定记录(商店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
答案 0 :(得分:1)
平均值只是值的总和除以值的数量(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));
答案 1 :(得分:0)
您可以在MySQL中创建视图。然后就不需要了。 View是一个虚拟表。在任何表格中的每次更改时,它都会自动更新。您不需要任何查询
create view result as select t1.code as code,(t1.value+t2.value+t3.value)/3 as value from `testcake`.`test1` as t1 JOIN `testcake`.`test2` as t2 ON t1.code = t2.code JOIN `testcake`.`test3` as t3 ON t1.code = t3.code