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 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来更新整个表,但是如果我只需要更新一个特定的父级,我应该把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;
答案 0 :(得分: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
我假设ID是您的主键,因此无需提供国家/地区。但是,如果确实需要,请将其放在子查询中的WHERE
子句中。