[英]MySQL update column value with max value from another column
I have a database with 2 tables: "services" and "service_performance" Those 2 tables have a SERVICE_ID column. 我有一个包含2个表的数据库:“服务”和“ service_performance”这2个表具有SERVICE_ID列。
In "services" the SERVICE_ID values are unique (each service has a single ID/entry). 在“服务”中,SERVICE_ID值是唯一的(每个服务都有一个ID /条目)。 In "service_performance" there is an AVERAGE_MEMORY column with multiple entries per service_id
在“ service_performance”中,有一个AVERAGE_MEMORY列,每个service_id包含多个条目
I am trying to update the MAX_VALUE column in "services" table with the highest AVERAGE_MEMORY value taken from the "service_performance" table. 我试图使用取自“ service_performance”表中的最高AVERAGE_MEMORY值来更新“ services”表中的MAX_VALUE列。
I know my query is wrong because it throws an error: 我知道我的查询是错误的,因为它会引发错误:
While 'service_performance.SERVICE_ID' does exist. 虽然“ service_performance.SERVICE_ID”确实存在。
Here is my query: 这是我的查询:
update _services
set MAX_VALUE = (SELECT MAX(AVERAGE_MEMORY) AS SERVICE_ID FROM service_performance)
where exists
(select *
from services
where `services`.`SERVICE_ID` = `service_performance`.`SERVICE_ID`);
You should find that this version works in MySQL: 您应该发现此版本可在MySQL中使用:
update services s join
(select service_id, MAX(AVERAGE_MEMORY) as maxmem
from service_performance
group by service_id
) sp
on s.service_id = sp.service_id
set s.MAX_VALUE = sp.maxmem;
Your version would work if it had the right table name in the where
clauses: 如果您的版本在
where
子句中具有正确的表名,则它将起作用:
update services
set MAX_VALUE = (SELECT MAX(AVERAGE_MEMORY) AS SERVICE_ID
FROM service_performance
WHERE `services`.`SERVICE_ID` = `service_performance`.`SERVICE_ID`)
where exists (select *
from service_performance
where `services`.`SERVICE_ID` = `service_performance`.`SERVICE_ID`
);
I am assuming that update _services
is a typo and should really be update services
. 我假设
update _services
是一个错字,应该确实是update services
。
MySQL is complaining because in this query there is no service_performance
table MySQL在抱怨,因为在此查询中没有
service_performance
表
Try it like this: 像这样尝试:
UPDATE _services s INNER JOIN service_performance p
ON s.SERVICE_ID=p.SERVICE_ID
SET s.MAX_VALUE=MAX(p.AVERAGE_MEMORY) GROUP BY p.SERVICE_ID
I don't have a database to test on, but firstly you haven't given the subquery an alias, so it doesn't know what service_performance.Service_ID is. 我没有要测试的数据库,但首先,您没有给子查询一个别名,因此它不知道什么是service_performance.Service_ID。
Secondly, in this context the subquery needs to return a single value rather than a table, so you may not be able to reference it. 其次,在这种情况下,子查询需要返回一个值而不是一个表,因此您可能无法引用它。 If adding the alias to the subquery doesn't work, then something like the following should work:
如果将别名添加到子查询不起作用,则应执行以下操作:
update _services
set MAX_VALUE = (SELECT MAX(AVERAGE_MEMORY) AS SERVICE_ID FROM service_performance
INNER JOIN
services
on services.SERVICE_ID = service_performance.SERVICE_ID)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.