编写一个sql的正确方法是使用{= 1}}的行= id为行的行的总和来更新所有type = 1
。
简单地说: update likesd set totals =所有总计的总和,其中parent =行的id,其中type = 1
type=1
期望的结果
"id" "type" "parent" "country" "totals"
"3" "1" "1" "US" "6"
"4" "2" "3" "US" "6"
"5" "3" "3" "US" "5"
我正在尝试(并失败)
"id" "type" "parent" "country" "totals"
"3" "1" "1" "US" "17" ->6+6+5=17
"4" "2" "3" "US" "6"
"5" "3" "3" "US" "5"
答案 0 :(得分:1)
这是执行你想要的命令
update likesd as upTbl
inner join
(select
tbl.id, tbl.totals + sum(tbl2.totals) as totals
from
likesd tbl
inner join likesd tbl2 ON tbl2.parent = tbl.id
where
tbl.type = 1
group by tbl.id) as results ON upTbl.id = results.id
set
upTbl.totals = results.totals;
在MySql 5.5上测试
答案 1 :(得分:1)
您可以使用in the MySQL Reference Manual所述的多表语法执行此操作:
update likesd a, (select parent, sum(totals) as tsum
from likesd group by parent) b
set a.totals = a.totals + b.tsum
where a.type = 1 and b.parent = a.id;
查询更新一行并产生:
+------+------+--------+---------+--------+
| id | type | parent | country | totals |
+------+------+--------+---------+--------+
| 3 | 1 | 1 | US | 17 |
| 4 | 2 | 3 | US | 6 |
| 5 | 3 | 3 | US | 5 |
+------+------+--------+---------+--------+
答案 2 :(得分:0)
请尝试以下查询:
with update_cte(parent,totals)
as(select parent, sum(totals)totalsNew
FROM likesd where type=1 group by parent)
update a
set a.totals=b.totals
from likesd a join update_cte b on a.id=b.parent
答案 3 :(得分:0)
update likesd
set totals = (
select a.childTotals
from (
select sum(totals) as childTotals
from likesd
) as a
)
where id = parent and type = 1;
编辑:根据MySQL Error 1093 - Can't specify target table for update in FROM clause,使用隐式临时表来允许更新嵌套SELECT语句中使用的同一个表。