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;
這不會在MySQL的:'你不能指定目標表 '父' 在FROM clause'更新。我之前做了類似的事情,然後在這個網站上找到了上面的sql。 – Norman
你忽略那個孩子是類型10(儘管在這個例子中只有父母和孩子) – Mzf
嗯 - 在我之前的例子中,是的。由於有父引用,除非我們正在處理損壞的數據,否則這應該是足夠的。 – mzedeler