[英]How can I select max value from one column and update another column with selected Max value
$query6 = "SELECT MAX(subject_total) AS max FROM results1 WHERE subjects = '{$result_subject}' AND class = '{$student_class}' AND term = '{$result_term}' AND session = '{$result_session}'";
$run_query6 = mysqli_query($connection, $query6);
while($run_query6 = mysqli_fetch_assoc($run_query6)) {
$max = $run_query6['max'];
}
$sql1 = "UPDATE results1 SET max = ".($max)." WHERE max = ".$max;
$run_query6 = mysqli_query($connection, $sql1); }
When I run the above code, $sql1 query doesn't update max column.当我运行上面的代码时, $sql1 查询不会更新 max 列。 Please help me fix this.
请帮我解决这个问题。 I need for the query to update max column with same max value.
我需要查询以相同的最大值更新 max 列。 Eg if 70 is max score in English, it will update all English rows with 70. But its not updating max column.
例如,如果 70 是英语的最高分数,它将用 70 更新所有英语行。但它不会更新 max 列。
You seem to want a window function:你似乎想要一个 window function:
select t.*,
max(subject_total) over (partition by subject) as subject_max
from t;
You just need one query to do the whole job:您只需要一个查询即可完成整个工作:
UPDATE
subjects
join
(SELECT subject, max(subject_total) as subject_max from subjects group by subject) m
on (subjects.subject = m.subject)
set
subjects.subject_max = m.subject_max;
The subquery selects the maximum value for each subject by using the GROUP BY clause.子查询使用 GROUP BY 子句为每个主题选择最大值。
The JOIN links the subquery to the main table on the subject
column so that the SET
can populate the values. JOIN 将子查询链接到
subject
列上的主表,以便SET
可以填充值。
Output: Output:
# id, user, subject, subject_total, subject_max
1, sam, English, 50, 51
2, abi, English, 51, 51
3, sam, agric, 52, 53
4, abi, agric, 53, 53
5, sam, ICT, 54, 55
6, abi, ICT, 55, 55
7, sam, French, 56, 58
8, abi, French, 57, 58
9, candy, French, 58, 58
Be careful with max
as a column name - I think it's a MySQL reserved word.小心使用
max
作为列名 - 我认为它是 MySQL 保留字。 My example uses subject_max
instead我的示例改用了
subject_max
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.