1

编写一个 sql 的正确方法是什么,它将type = 1用 parent = id of row with 的行的总和来更新所有内容type=1

简单地说:更新 likesd set totals = 所有总数的总和 where parent = id of row where 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"

我正在尝试(但失败了)

UPDATE  likesd a
        INNER JOIN (
        SELECT  parent, sum(totals) totalsNew
        FROM likesd
        WHERE b.parent = a.id 
        GROUP BY parent
        ) b ON a.id = b.parent
        SET a.totals = b.totalsNew;
4

4 回答 4

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 上测试

于 2013-09-27T20:32:31.593 回答
1

您可以使用MySQL 参考手册中描述的多表语法来做到这一点:

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 |
+------+------+--------+---------+--------+
于 2013-09-27T20:42:07.257 回答
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
于 2013-09-27T19:27:44.993 回答
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 错误 1093 - Can't specify target table for update in FROM 子句,使用隐式临时表允许更新嵌套 SELECT 语句中使用的同一个表。

于 2013-09-27T19:29:55.220 回答