0

SQL小提琴在这里

"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;
4

1 回答 1

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

于 2013-05-26T09:10:18.757 回答