2013-05-26 51 views
0

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

這應該工作。你有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

+0

這不會在MySQL的:'你不能指定目標表 '父' 在FROM clause'更新。我之前做了類似的事情,然後在這個網站上找到了上面的sql。 – Norman

+0

你忽略那個孩子是類型10(儘管在這個例子中只有父母和孩子) – Mzf

+0

嗯 - 在我之前的例子中,是的。由於有父引用,除非我們正在處理損壞的數據,否則這應該是足夠的。 – mzedeler