Mysql 使用同一表中的数据更新行
编写一个sql的正确方法是什么?该sql将使用行总数更新所有Mysql 使用同一表中的数据更新行,mysql,sql,Mysql,Sql,编写一个sql的正确方法是什么?该sql将使用行总数更新所有type=1,其中parent=id为type=1 简言之: update likesd set totals=所有总计的总和,其中父项=行的id,其中类型=1 "id" "type" "parent" "country" "totals" "3" "1" "1" "US" "6" "4" "2" "3" "US" "6" "5
type=1
,其中parent=id为type=1
简言之:
update likesd set totals=所有总计的总和,其中父项=行的id,其中类型=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"
我尝试过(但失败了)
请尝试以下查询:
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
编辑:根据,使用隐式临时表允许对嵌套SELECT语句中使用的相同表进行更新。以下是执行所需操作的命令
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上进行了测试,您可以使用以下描述的多表语法执行此操作: 查询将更新一行并生成以下结果:
+------+------+--------+---------+--------+
| id | type | parent | country | totals |
+------+------+--------+---------+--------+
| 3 | 1 | 1 | US | 17 |
| 4 | 2 | 3 | US | 6 |
| 5 | 3 | 3 | US | 5 |
+------+------+--------+---------+--------+
你在“失败”中得到了什么结果?我会说,保持原样,根据孩子/父母的关系,显示总数。这样,在某些地方就没有“计算”字段,而在其他地方就没有得到计算字段的数学。例如,将其留在表示层。@Elias。我在“where子句”中得到“Unknown column”b.parent“ID 3是否总是得到总数,或者如果说ID 5是父项,那么应该只得到父项为5的ID的总数吗?
Type=1
将得到总数。因此,如果有许多type=1
,那么所有这些都需要使用各自子级的sums()进行更新。MySQL还不支持CTE。这就给出了:您不能在FROM子句中为update指定目标表'likesd'
如何?对不起,我的机器上只运行MS-SQL,所以我在猜测/阅读MySQL语义。
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;
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 |
+------+------+--------+---------+--------+