[英]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.