[英]How do you add two values from the same table and store in calculated record in the same table?
嗨,我這里有一張桌子:
equipment
ID, Owner, Type, Count
1 Bob phone 10
2 Larry computer 11
1 Bob computer 11
我想做的是將ID為1的Bob的計算機添加到ID為2的Larry's的計算機中。我試圖增加計數。 計數應為11 + 11 = 22。 ID 2的新計算機數應為22,並應在數據庫中按以下方式更新:
equipment
ID, Owner, Type, Count
1 Bob phone 10
2 Larry computer 22
1 Bob computer 11
如果Bob沒有任何計算機,這意味着沒有ID = 2的記錄,則應創建該記錄。
這是我的SQL:
INSERT INTO EQUIPMENT(`ID`, `OWNER`, `TYPE`, `COUNT`)
SELECT 1 as t.ID, t.OWNER, t.TYPE, t.COUNT
FROM EQUIPMENT t
WHERE t.ID = 2
on duplicate key
update
COUNT = COUNT + t.COUNT;
為什么使用insert
來更新行?
update equipment e cross join
(select e1.* from equipment e1 where e1.id = 1) as e1
select e.count = e.count + e1.count
where e.id = 2;
像這樣的東西
UPDATE Yourtable a
JOIN Yourtable b
ON a.NAME = b.NAME
AND a.ID = b.ID + 1
SET a.Count = a.Count + b.Count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.