更新父母与父母明智和国家明智的总数的count()

时间:2013-05-26 09:06:57

标签: mysql sql

SQL小提琴here

"id"    "type"  "parent"    "country"   "totals"
1       3       0           US          0       //Desired output 5
2       10      1           US          0
3       10      1           US          0
4       10      1           US          0
5       10      1           US          0
6       10      1           US          0

7       3       0           US          0       //Desired output 5
8       10      7           US          0
9       10      7           US          0
10      10      7           US          0
11      10      7           US          0
12      10      7           US          0

13      3       0           SE          0       //Desired output 1
14      10      13          SE          0

15      3       0           SE          0       //Desired output 3
16      10      15          SE          0
17      10      15          SE          0
18      10      15          SE          0

在上表中,我正在尝试更新所有父母的子女数(how many children each has)

父母是type 3,孩子是type 10,而且这个国家就在旁边。

我要做的是:

`select count(*) as totalChildren ,parent,country where type= 10` then
`update table set totals = totalChildren where parent = parent from above and country = country from above`.

我在这些方面做了一些事情,但我似乎无处可去。你能帮我吗?

UPDATE  likesd a
        INNER JOIN
        (
            SELECT  country, parent, count(id) totalChildren
            FROM    likesd
            WHERE   type = 10
            GROUP   BY parent
        ) b ON a.country = b.country and a.parent=b.parent
SET     a.totals = b.totalChildren
WHERE   a.type = 3 and a.country = b.country;

编辑 - 工作答案

UPDATE  likesd a
        INNER JOIN
        (
            SELECT  country, parent, count(id) totalChildren
            FROM    likesd
            WHERE   type = 10
            GROUP   BY parent
        ) b ON a.id=b.parent and a.country = b.country
SET     a.totals = b.totalChildren
WHERE   a.type = 3 and a.id = b.parent and a.country = b.country;

1 个答案:

答案 0 :(得分:1)

这应该有效。您的a.parent = b.parent位于a.id = b.parent

UPDATE  likesd a
    INNER JOIN
    (SELECT  parent, count(id) totalChildren
       FROM    likesd
      WHERE   type = 10
      GROUP   BY parent) b ON a.id=b.parent
SET     a.totals = b.totalChildren
WHERE   a.type = 3

(抱歉奇怪的格式化。)

SQL小提琴:http://sqlfiddle.com/#!2/0c5b0d/1