gpt4 book ai didi

mysql - 使用另一个 SELECT 更新表,但字段为 SUM(someField)

转载 作者:可可西里 更新时间:2023-11-01 08:21:02 26 4
gpt4 key购买 nike

基本上我有这样的东西:

UPDATE
Table
SET
Table.col1 = other_table.col1,
FROM
Table
INNER JOIN
other_table
ON
Table.id = other_table.id

问题是我想更新 col1 的选择如下:

SELECT SUM(col1) FROM other_table WHERE Table.id = other_table.id AND period > 2011

编辑

正确答案:

UPDATE bestall  
INNER JOIN (SELECT bestid,SUM(view) as v,SUM(rawView) as rv
FROM beststat
WHERE period > 2011 GROUP BY bestid) as t1
ON bestall.bestid = t1.bestid
SET view = t1.v, rawview = t1.rv

最佳答案

您不能在 set 子句中直接使用聚合。一种解决方法是子查询:

update  your_table as yt
left join
(
select id
, count(*) as cnt
from other_table
where period < 4
group by
id
) as ot
on yt.id = ot.id
set col1 = coalesce(ot.cnt,0)

Example at SQL Fiddle.

关于mysql - 使用另一个 SELECT 更新表,但字段为 SUM(someField),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10261977/

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