2013-05-26 24 views
0

SQL小提琴hereWhere子句將在這個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 a parent has. I'll supply the parent id and country)的計數父。

父母是type 3和孩子是type 10和國家代碼是在一邊。

我試圖做的是:

$parent = 10; 
$country = 'US'; 

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

我目前使用下面的SQL更新整個表,但如果我只需要更新一個praticular父我應該在哪裏放置在where子句中下面的sql。我對此有點困惑。

UPDATE likesd a // where parent = $parent and country = $country - where should this go? 
     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

既然你只有一個孩子父母的關係,這應該工作:

UPDATE likesd l 
JOIN (
    SELECT COUNT(1) cnt, parent 
    FROM likesd 
    WHERE parent = ? 
    GROUP BY parent 
) l2 ON l.id = l2.parent 
SET l.totals = l2.cnt 

Update Fiddle Demo

我假設ID是你的主鍵,從而不需要供應國家。如果您確實需要,請將其置於子查詢中的WHERE子句中。